import { Router, Request, Response } from 'express';
import { HealthService } from './health.service';

export class HealthController {
  public router: Router;

  constructor(private healthService: HealthService) {
    this.router = Router();
    this.initializeRoutes();
  }

  private initializeRoutes(): void {
    /**
     * @swagger
     * /health:
     *   get:
     *     summary: Get health status
     *     tags: [Health]
     *     responses:
     *       200:
     *         description: Service is healthy
     *       503:
     *         description: Service is unhealthy
     */
    this.router.get('/', this.getHealth.bind(this));

    /**
     * @swagger
     * /health/live:
     *   get:
     *     summary: Liveness probe
     *     tags: [Health]
     *     responses:
     *       200:
     *         description: Service is alive
     */
    this.router.get('/live', this.getLiveness.bind(this));

    /**
     * @swagger
     * /health/ready:
     *   get:
     *     summary: Readiness probe
     *     tags: [Health]
     *     responses:
     *       200:
     *         description: Service is ready
     *       503:
     *         description: Service is not ready
     */
    this.router.get('/ready', this.getReadiness.bind(this));
  }

  private async getHealth(req: Request, res: Response): Promise<void> {
    try {
      const health = await this.healthService.getHealth();
      const statusCode = health.status === 'healthy' ? 200 : health.status === 'degraded' ? 200 : 503;
      res.status(statusCode).json(health);
    } catch (error) {
      res.status(503).json({
        status: 'unhealthy',
        timestamp: new Date().toISOString(),
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }

  private async getLiveness(req: Request, res: Response): Promise<void> {
    const result = await this.healthService.getLiveness();
    res.status(200).json(result);
  }

  private async getReadiness(req: Request, res: Response): Promise<void> {
    const result = await this.healthService.getReadiness();
    const statusCode = result.status === 'ready' ? 200 : 503;
    res.status(statusCode).json(result);
  }
}
