/**
 * Liveness Probe Endpoint
 * Agent 4: Production Deployment
 *
 * GET /api/health/live
 * Returns liveness status for Kubernetes/container orchestration.
 * Used to determine if the application process is running.
 */

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

interface LiveResponse {
  alive: boolean;
  uptime: number;
  timestamp: string;
}

interface ErrorResponse {
  alive: boolean;
  error: string;
  timestamp: string;
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<LiveResponse | ErrorResponse>
) {
  if (req.method !== 'GET') {
    res.setHeader('Allow', ['GET']);
    return res.status(405).json({
      alive: false,
      error: `Method ${req.method} is not allowed`,
      timestamp: new Date().toISOString(),
    });
  }

  try {
    const liveness = await healthChecks.checkLiveness();
    const uptime = healthChecks.getUptime();

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

    return res.status(200).json({
      alive: liveness.status === 'ok',
      uptime,
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    // If we can respond at all, we're technically alive
    return res.status(200).json({
      alive: true,
      uptime: healthChecks.getUptime(),
      timestamp: new Date().toISOString(),
    });
  }
}
