/**
 * GET /api/admin/brand-health/status
 *
 * Returns current health status for all active brands — open alerts
 * plus the most recent resolved alert per brand for historical context.
 * Powers the Brand Health card in the admin tools page.
 */

import { NextResponse } from "next/server";
import { requireSuperadmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";
export const maxDuration = 30;

export async function GET() {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const brands = await prisma.brand.findMany({
    where: { status: { not: "deleted" }, trackedSite: { isNot: null }, isDemo: false },
    select: {
      id: true,
      name: true,
      domain: true,
      trackedSite: { select: { siteId: true } },
      healthAlerts: {
        orderBy: { createdAt: "desc" },
        take: 2,
        select: {
          id: true,
          status: true,
          firstDetectedAt: true,
          alertSentAt: true,
          resolvedAt: true,
          expectedRate: true,
          actualRate: true,
          dropPct: true,
          consecutiveHoursDegraded: true,
          lastCheckedAt: true,
        },
      },
    },
    orderBy: { name: "asc" },
  });

  const rows = brands.map((b) => {
    const openAlert = b.healthAlerts.find((a) => a.status !== "resolved") ?? null;
    const lastResolved = b.healthAlerts.find((a) => a.status === "resolved") ?? null;
    return {
      brandId: b.id,
      brandName: b.name,
      domain: b.domain,
      siteId: b.trackedSite?.siteId ?? null,
      healthStatus: openAlert?.status ?? "healthy",
      openAlert,
      lastResolved,
    };
  });

  const summary = {
    total: rows.length,
    healthy: rows.filter((r) => r.healthStatus === "healthy").length,
    degraded: rows.filter((r) => r.healthStatus === "degraded").length,
    down: rows.filter((r) => r.healthStatus === "down").length,
  };

  return NextResponse.json({ summary, brands: rows });
}
