/**
 * Health Controller
 * REST endpoints for health, liveness and readiness probes
 * Compatible with erp-core health.controller
 *
 * @module Health
 */

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 {
    this.router.get('/', this.getHealth.bind(this));
    this.router.get('/live', this.getLiveness.bind(this));
    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);
  }
}
