/**
 * GET /api/admin/brands/[brandId]/site-tag-status
 *
 * Lightweight DB read — returns whether the brand's Site Tag has fired.
 * Used by the admin audit trigger UI to show the detection indicator.
 */

import { NextResponse } from "next/server";
import { requireSuperadmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";
import { isSiteTagActive } from "@/lib/brand/site-tag-active";

export const dynamic = "force-dynamic";

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ brandId: string }> },
) {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const { brandId } = await params;

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

  if (!brand) {
    return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  }

  const detected = await isSiteTagActive(brandId);
  const lastEventAt = brand.trackedSite?.lastEventAt?.toISOString() ?? null;

  return NextResponse.json({ detected, lastEventAt });
}
