/**
 * POST /api/admin/invalidate-phone-pattern
 *
 * Marks ALL SiteConversion rows with detectionMethod='phone_pattern'
 * across all brands as invalidated. These rows stay in the DB for
 * audit/forensic purposes but are excluded from all metrics via the
 * active-conversion-filter.
 *
 * Returns per-brand counts of invalidated rows.
 */

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

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

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

  const brands = await prisma.brand.findMany({
    where: { status: { not: "deleted" } },
    select: { id: true, name: true },
  });

  const results: Array<{ brand: string; invalidated: number }> = [];
  let total = 0;

  for (const brand of brands) {
    const updated = await prisma.siteConversion.updateMany({
      where: {
        brandId: brand.id,
        detectionMethod: "phone_pattern",
        invalidatedReason: null,
      },
      data: { invalidatedReason: "phone_pattern_deprecated" },
    }).catch(() => ({ count: 0 }));

    results.push({ brand: brand.name, invalidated: updated.count });
    total += updated.count;
  }

  return NextResponse.json({ total, results });
}
