import { NextResponse } from "next/server";
import { getSupabaseAdmin } from "@/lib/supabase/server";

/**
 * GET /api/health
 *
 * Lightweight health check endpoint. No auth required.
 * Checks: app running, DB reachable, memory usage, uptime.
 */
export async function GET() {
  const start = Date.now();
  const checks: Record<string, { ok: boolean; ms?: number; error?: string; detail?: string }> = {};

  // App check (always passes if we get here)
  checks.app = { ok: true, ms: 0 };

  // Database check
  try {
    const dbStart = Date.now();
    const admin = getSupabaseAdmin();
    const { error } = await admin.from("profiles").select("id", { count: "exact", head: true });
    const dbMs = Date.now() - dbStart;
    checks.database = { ok: !error, ms: dbMs, ...(error && { error: error.message }) };
  } catch (err) {
    checks.database = { ok: false, error: err instanceof Error ? err.message : "DB unreachable" };
  }

  // Memory check
  const mem = process.memoryUsage();
  const heapUsedMB = Math.round(mem.heapUsed / 1024 / 1024);
  const heapTotalMB = Math.round(mem.heapTotal / 1024 / 1024);
  const rssMB = Math.round(mem.rss / 1024 / 1024);
  checks.memory = {
    ok: heapUsedMB < 512, // Alert if heap > 512MB
    detail: `heap: ${heapUsedMB}/${heapTotalMB}MB, rss: ${rssMB}MB`,
  };

  // Uptime
  const uptimeSeconds = Math.round(process.uptime());
  const uptimeHours = Math.round(uptimeSeconds / 3600 * 10) / 10;

  const allOk = Object.values(checks).every((c) => c.ok);
  const totalMs = Date.now() - start;

  return NextResponse.json({
    status: allOk ? "healthy" : "degraded",
    uptime: `${uptimeHours}h`,
    responseMs: totalMs,
    checks,
    timestamp: new Date().toISOString(),
  }, { status: allOk ? 200 : 503 });
}
