// Health Check Routes
// Liveness and readiness probes for Kubernetes/container orchestration

import { Router, Request, Response } from 'express';
import prisma from '@/shared/database/prisma';
import { logger } from '@/infrastructure/monitoring/logger';

const router = Router();

/**
 * @route GET /health
 * @desc Basic health check
 * @access Public
 */
router.get('/', async (_req: Request, res: Response) => {
  res.json({
    status: 'healthy',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
  });
});

/**
 * @route GET /health/live
 * @desc Liveness probe - indicates if the service is running
 * @access Public
 */
router.get('/live', async (_req: Request, res: Response) => {
  res.json({
    status: 'alive',
    timestamp: new Date().toISOString(),
  });
});

/**
 * @route GET /health/ready
 * @desc Readiness probe - indicates if the service is ready to accept traffic
 * @access Public
 */
router.get('/ready', async (_req: Request, res: Response) => {
  try {
    // Check database connectivity
    await prisma.$queryRaw`SELECT 1`;

    res.json({
      status: 'ready',
      timestamp: new Date().toISOString(),
      checks: {
        database: 'connected',
      },
    });
  } catch (error) {
    logger.error('Readiness check failed', {
      error: error instanceof Error ? error.message : 'Unknown error',
    });

    res.status(503).json({
      status: 'not_ready',
      timestamp: new Date().toISOString(),
      checks: {
        database: 'disconnected',
      },
      error: error instanceof Error ? error.message : 'Unknown error',
    });
  }
});

/**
 * @route GET /health/startup
 * @desc Startup probe - indicates if the service has finished starting
 * @access Public
 */
router.get('/startup', async (_req: Request, res: Response) => {
  // Check if critical services are initialized
  const checks: Record<string, string> = {};

  try {
    // Database check
    await prisma.$queryRaw`SELECT 1`;
    checks.database = 'ready';
  } catch (error) {
    checks.database = 'not_ready';
  }

  const allReady = Object.values(checks).every((status) => status === 'ready');

  if (allReady) {
    res.json({
      status: 'started',
      timestamp: new Date().toISOString(),
      checks,
    });
  } else {
    res.status(503).json({
      status: 'starting',
      timestamp: new Date().toISOString(),
      checks,
    });
  }
});

export default router;
