/**
 * GET /api/brands/[brandId]/health-alert
 *
 * Returns the open BrandHealthAlert (status="down") for a brand, if any.
 * Used by the site-tag-analytics page to show an ingest degraded banner.
 * Requires user to be authenticated (no superadmin required — the page
 * is brand-scoped and visible to the brand's org members).
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ brandId: string }> },
) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { brandId } = await params;

  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    select: { organization: { select: { memberships: { select: { userId: true } } } } },
  }).catch(() => null);

  if (!brand || !brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ alert: null });
  }

  const alert = await prisma.brandHealthAlert.findFirst({
    where: { brandId, status: "down" },
    orderBy: { createdAt: "desc" },
    select: {
      id: true,
      status: true,
      firstDetectedAt: true,
      expectedRate: true,
      actualRate: true,
      dropPct: true,
      consecutiveHoursDegraded: true,
    },
  }).catch(() => null);

  return NextResponse.json({ alert });
}
