import { NextResponse } from "next/server";
import { checkDatabaseHealth } from "@/lib/health-checks";

/**
 * Main Health Check Endpoint
 *
 * Returns overall system health with basic metrics
 * Use this for load balancer health checks and quick status verification
 *
 * Response Codes:
 * - 200: All systems healthy
 * - 503: One or more systems degraded
 */
export async function GET() {
  const startTime = Date.now();

  // Basic health check
  const healthCheck = {
    status: "healthy",
    timestamp: new Date().toISOString(),
    service: "mawidi",
    version: process.env.NEXT_PUBLIC_APP_VERSION || "0.1.0",
    environment: process.env.NODE_ENV || "development",
    uptime: process.uptime(),
    memory: {
      used: Math.round(process.memoryUsage().heapUsed / 1024 / 1024),
      total: Math.round(process.memoryUsage().heapTotal / 1024 / 1024),
      rss: Math.round(process.memoryUsage().rss / 1024 / 1024),
      unit: "MB",
    },
    responseTime: 0, // Will be set below
  };

  // Check database health (quick check)
  try {
    const dbHealth = await checkDatabaseHealth();
    if (!dbHealth.healthy) {
      healthCheck.status = "degraded";
    }
  } catch {
    healthCheck.status = "unhealthy";
  }

  // Set response time
  healthCheck.responseTime = Date.now() - startTime;

  const statusCode = healthCheck.status === "healthy" ? 200 : 503;

  return NextResponse.json(healthCheck, {
    status: statusCode,
    headers: {
      "Cache-Control": "no-cache, no-store, must-revalidate",
      Pragma: "no-cache",
      Expires: "0",
    },
  });
}

/**
 * HEAD request for simple health check
 * Used by load balancers and monitoring tools that don't need response body
 */
export async function HEAD() {
  try {
    const dbHealth = await checkDatabaseHealth();
    const statusCode = dbHealth.healthy ? 200 : 503;
    return new Response(null, { status: statusCode });
  } catch {
    return new Response(null, { status: 503 });
  }
}
