/**
 * POST /api/admin/demo-brand/cleanup
 * ────────────────────────────────────
 * Deletes all seed data for a demo brand (isDemo: true).
 *
 * Hard guard: refuses to run if brand.isDemo is false.
 * Deletes in FK-safe order to avoid constraint violations.
 * Returns per-table deletion counts.
 *
 * Does NOT delete the brand itself — call /api/admin/demo-brand/create
 * again after cleanup to re-seed from a clean slate.
 *
 * Auth: x-admin-secret header
 * Body: { brandId: string, deleteBrand?: boolean }
 */

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

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

export async function POST(req: Request) {
  const secret = req.headers.get("x-admin-secret");
  if (!secret || secret !== process.env.ADMIN_SECRET) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await req.json().catch(() => null) as { brandId?: string; deleteBrand?: boolean } | null;
  if (!body?.brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const brand = await prisma.brand.findUnique({
    where: { id: body.brandId },
    include: { trackedSite: { select: { id: true } } },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.isDemo) {
    return NextResponse.json({ error: "REFUSED: brand.isDemo is false — cleanup only runs on demo brands" }, { status: 403 });
  }

  const counts: Record<string, number> = {};

  // 1. Site-tag events (deepest child tables first)
  const trackedSiteId = brand.trackedSite?.id;
  if (trackedSiteId) {
    const { count: evtCount } = await prisma.trackedEvent.deleteMany({ where: { trackedSiteId } });
    counts.trackedEvents = evtCount;
    const { count: sessCount } = await prisma.trackedSession.deleteMany({ where: { trackedSiteId } });
    counts.trackedSessions = sessCount;
  } else {
    counts.trackedEvents = 0;
    counts.trackedSessions = 0;
  }

  // 2. Site-tag brand-scoped tables
  const { count: heatCount } = await prisma.heatmapEvent.deleteMany({ where: { brandId: body.brandId } });
  counts.heatmapEvents = heatCount;

  const { count: siteEvtCount } = await prisma.siteEvent.deleteMany({ where: { brandId: body.brandId } });
  counts.siteEvents = siteEvtCount;

  const { count: convCount } = await prisma.siteConversion.deleteMany({ where: { brandId: body.brandId } });
  counts.siteConversions = convCount;

  const { count: attrPathCount } = await prisma.attributionPath.deleteMany({ where: { brandId: body.brandId } });
  counts.attributionPaths = attrPathCount;

  const { count: aiAttrCount } = await prisma.aiAttribution.deleteMany({ where: { brandId: body.brandId } });
  counts.aiAttributions = aiAttrCount;

  const { count: visitorCount } = await prisma.visitorProfile.deleteMany({ where: { brandId: body.brandId } });
  counts.visitorProfiles = visitorCount;

  const { count: hhCount } = await prisma.householdCluster.deleteMany({ where: { brandId: body.brandId } });
  counts.householdClusters = hhCount;

  const { count: adClickCount } = await prisma.adClickEvent.deleteMany({ where: { brandId: body.brandId } });
  counts.adClickEvents = adClickCount;

  // 3. GSC / GA4 data
  const { count: gscQCount } = await prisma.gscQuery.deleteMany({ where: { brandId: body.brandId } });
  counts.gscQueries = gscQCount;

  const { count: gscPCount } = await prisma.gscPage.deleteMany({ where: { brandId: body.brandId } });
  counts.gscPages = gscPCount;

  const { count: metricCount } = await prisma.metricSnapshot.deleteMany({ where: { brandId: body.brandId } });
  counts.metricSnapshots = metricCount;

  // 4. Rank tracker
  // KeywordRanking is cascade-deleted when TrackedKeyword is deleted
  const { count: tkCount } = await prisma.trackedKeyword.deleteMany({ where: { brandId: body.brandId } });
  counts.trackedKeywords = tkCount;

  // 5. AI visibility
  const { count: aiCheckCount } = await prisma.aiVisibilityCheck.deleteMany({ where: { brandId: body.brandId } });
  counts.aiVisibilityChecks = aiCheckCount;

  const { count: aiQueryCount } = await prisma.aiVisibilityQuery.deleteMany({ where: { brandId: body.brandId } });
  counts.aiVisibilityQueries = aiQueryCount;

  // 6. Competitor intel (CompetitorPage cascade-deleted with Competitor)
  const { count: compCount } = await prisma.competitor.deleteMany({ where: { brandId: body.brandId } });
  counts.competitors = compCount;

  // 7. Backlinks (Backlink rows reference BacklinkSnapshot via snapshotId)
  const { count: blCount } = await prisma.backlink.deleteMany({ where: { brandId: body.brandId } });
  counts.backlinks = blCount;

  const { count: blsCount } = await prisma.backlinkSnapshot.deleteMany({ where: { brandId: body.brandId } });
  counts.backlinkSnapshots = blsCount;

  // 8. Dashboard data
  await prisma.dashboardData.deleteMany({ where: { brandId: body.brandId } }).catch(() => null);
  counts.dashboardData = 1;

  // 9. Optionally delete the brand itself (and everything else via cascade)
  if (body.deleteBrand === true) {
    await prisma.brand.delete({ where: { id: body.brandId } });
    counts.brand = 1;
    console.info(`[demo-brand/cleanup] brand=${body.brandId} deleted`);
  } else {
    console.info(`[demo-brand/cleanup] brand=${body.brandId} seed data cleared (brand retained)`);
  }

  return NextResponse.json({ ok: true, brandId: body.brandId, brandDeleted: body.deleteBrand === true, counts });
}
