/**
 * GET /api/admin/health — system health check.
 */
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

async function check(name: string, fn: () => Promise<boolean>): Promise<{ name: string; status: string }> {
  try { return { name, status: (await fn()) ? "healthy" : "degraded" }; }
  catch { return { name, status: "down" }; }
}

export async function GET() {
  const auth = await requireAdmin();
  if (!auth.ok) return NextResponse.json({ error: "Forbidden" }, { status: auth.status });

  const checks = await Promise.all([
    check("database", async () => { await prisma.$queryRaw`SELECT 1`; return true; }),
    check("google_api", async () => { const r = await fetch("https://www.googleapis.com/discovery/v1/apis?maxResults=1"); return r.ok; }),
    check("anthropic_api", async () => { return !!process.env.ANTHROPIC_API_KEY; }),
    check("smtp", async () => { return !!process.env.SMTP_HOST; }),
    check("twilio", async () => { return !!process.env.TWILIO_ACCOUNT_SID; }),
  ]);

  const allHealthy = checks.every((c) => c.status === "healthy");
  return NextResponse.json({ status: allHealthy ? "healthy" : "degraded", checks });
}
