const express = require('express');
const {
  getHealthStatus,
  getMetrics,
  checkDatabaseHealth,
  checkRedisHealth,
} = require('../services/monitoringService');

const router = express.Router();

/**
 * @swagger
 * /health:
 *   get:
 *     summary: 健康检查
 *     description: 检查服务器及所有依赖服务的运行状态
 *     tags: [Health]
 *     responses:
 *       200:
 *         description: 服务器运行正常
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 data:
 *                   type: object
 *                   properties:
 *                     status:
 *                       type: string
 *                       enum: [healthy, degraded, unhealthy]
 *                     timestamp:
 *                       type: string
 *                       format: date-time
 *                     uptime:
 *                       type: number
 *                       description: 服务器运行时间（秒）
 *                     version:
 *                       type: string
 *                     nodeVersion:
 *                       type: string
 *                     services:
 *                       type: object
 *                       properties:
 *                         database:
 *                           type: object
 *                         redis:
 *                           type: object
 *                     memory:
 *                       type: object
 *       503:
 *         description: 服务不可用
 */
router.get('/', async (req, res) => {
  try {
    const health = await getHealthStatus();
    const statusCode = health.status === 'healthy' ? 200 : 503;

    res.status(statusCode).json({
      success: health.status === 'healthy',
      data: health,
    });
  } catch (error) {
    res.status(503).json({
      success: false,
      data: {
        status: 'unhealthy',
        timestamp: new Date().toISOString(),
        error: error.message,
      },
    });
  }
});


/**
 * @swagger
 * /health/live:
 *   get:
 *     summary: 存活检查
 *     description: 简单的存活检查，用于Kubernetes liveness probe
 *     tags: [Health]
 *     responses:
 *       200:
 *         description: 服务存活
 */
router.get('/live', (req, res) => {
  res.json({
    success: true,
    data: {
      status: 'alive',
      timestamp: new Date().toISOString(),
    },
  });
});

/**
 * @swagger
 * /health/ready:
 *   get:
 *     summary: 就绪检查
 *     description: 检查服务是否准备好接收流量，用于Kubernetes readiness probe
 *     tags: [Health]
 *     responses:
 *       200:
 *         description: 服务就绪
 *       503:
 *         description: 服务未就绪
 */
router.get('/ready', async (req, res) => {
  try {
    const [dbHealth, redisHealth] = await Promise.all([
      checkDatabaseHealth(),
      checkRedisHealth(),
    ]);

    const isReady =
      dbHealth.status === 'healthy' &&
      (redisHealth.status === 'healthy' || redisHealth.status === 'not_initialized');

    if (isReady) {
      res.json({
        success: true,
        data: {
          status: 'ready',
          timestamp: new Date().toISOString(),
        },
      });
    } else {
      res.status(503).json({
        success: false,
        data: {
          status: 'not_ready',
          timestamp: new Date().toISOString(),
          services: {
            database: dbHealth.status,
            redis: redisHealth.status,
          },
        },
      });
    }
  } catch (error) {
    res.status(503).json({
      success: false,
      data: {
        status: 'not_ready',
        timestamp: new Date().toISOString(),
        error: error.message,
      },
    });
  }
});

/**
 * @swagger
 * /metrics:
 *   get:
 *     summary: 获取系统指标
 *     description: 获取系统运行指标，包括请求统计、响应时间、内存使用等
 *     tags: [Health]
 *     responses:
 *       200:
 *         description: 指标数据
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   type: object
 *                   properties:
 *                     uptime:
 *                       type: number
 *                       description: 运行时间（秒）
 *                     requests:
 *                       type: object
 *                       properties:
 *                         total:
 *                           type: number
 *                         success:
 *                           type: number
 *                         error:
 *                           type: number
 *                         errorRate:
 *                           type: string
 *                     responseTime:
 *                       type: object
 *                       properties:
 *                         average:
 *                           type: number
 *                         min:
 *                           type: number
 *                         max:
 *                           type: number
 *                     memory:
 *                       type: object
 */
router.get('/metrics', (req, res) => {
  const metricsData = getMetrics();

  res.json({
    success: true,
    data: metricsData,
  });
});

module.exports = router;
