/**
 * Health Check Endpoint
 * Agent 4: Production Deployment
 *
 * GET /api/health
 * Returns overall application health status with component checks.
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { healthChecks, HealthStatus } from '../../../lib/monitoring';
import { withLogging } from '../../../lib/logging';

interface HealthResponse extends HealthStatus {}

interface ErrorResponse {
  error: string;
  message: string;
}

async function handler(
  req: NextApiRequest,
  res: NextApiResponse<HealthResponse | ErrorResponse>
) {
  if (req.method !== 'GET') {
    res.setHeader('Allow', ['GET']);
    return res.status(405).json({
      error: 'Method Not Allowed',
      message: `Method ${req.method} is not allowed`,
    });
  }

  try {
    const health = await healthChecks.runAll();

    // Set appropriate status code based on health
    const statusCode = health.status === 'healthy' ? 200 : health.status === 'degraded' ? 200 : 503;

    // Add cache headers - don't cache health checks
    res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
    res.setHeader('Pragma', 'no-cache');
    res.setHeader('Expires', '0');

    return res.status(statusCode).json(health);
  } catch (error) {
    return res.status(503).json({
      error: 'Health Check Failed',
      message: error instanceof Error ? error.message : 'Unknown error',
    });
  }
}

export default withLogging(handler);
