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

/**
 * Detailed Health Check Endpoint
 *
 * Returns comprehensive health status for all subsystems
 * Use this for monitoring dashboards and detailed diagnostics
 *
 * Response Codes:
 * - 200: All systems healthy
 * - 207: Partial success (some systems degraded)
 * - 503: Critical systems down
 */
export async function GET(request: Request) {
  const startTime = Date.now();
  const { searchParams } = new URL(request.url);
  const includeMetrics = searchParams.get("metrics") === "true";

  // Run all health checks in parallel
  const [database, email] = await Promise.allSettled([
    checkDatabaseHealth(),
    checkEmailHealth(),
  ]);

  // Extract results
  const checks = {
    convex:
      database.status === "fulfilled"
        ? database.value
        : { healthy: false, error: "Check failed" },
    email:
      email.status === "fulfilled"
        ? email.value
        : { healthy: false, error: "Check failed" },
  };

  // Determine overall status
  const criticalSystems = [checks.convex];
  const allCriticalHealthy = criticalSystems.every((c) => c.healthy);

  const optionalSystems = [checks.email];
  const anyOptionalUnhealthy = optionalSystems.some((c) => !c.healthy);

  let overallStatus: "healthy" | "degraded" | "unhealthy";
  let statusCode: number;

  if (allCriticalHealthy && !anyOptionalUnhealthy) {
    overallStatus = "healthy";
    statusCode = 200;
  } else if (allCriticalHealthy && anyOptionalUnhealthy) {
    overallStatus = "degraded";
    statusCode = 207; // Multi-Status
  } else {
    overallStatus = "unhealthy";
    statusCode = 503;
  }

  // Build response
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const response: any = {
    status: overallStatus,
    timestamp: new Date().toISOString(),
    service: "mawidi",
    version: process.env.NEXT_PUBLIC_APP_VERSION || "0.1.0",
    environment: process.env.NODE_ENV || "development",
    responseTime: Date.now() - startTime,
    checks,
  };

  // Add system metrics if requested
  if (includeMetrics) {
    response.metrics = getSystemMetrics();
  }

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