/**
 * POST /api/admin/debug/purge-ga4-snapshots?brandId=xxx
 *
 * Deletes MetricSnapshot rows with source='ga4' where the conversions
 * field is suspiciously high (conversions > sessions * 10). These are
 * rows where GA4's "conversions" metric returned eventCount-level
 * numbers because the GA4 property had common events (page_view,
 * scroll) incorrectly marked as key events.
 *
 * After purging, the next integration-sync run will re-fetch clean
 * data from the GA4 API.
 *
 * Superadmin-only. Pass ?brandId=xxx to purge a specific brand, or
 * omit to scan all brands.
 */

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

export const dynamic = "force-dynamic";

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

  const { searchParams } = new URL(req.url);
  const targetBrandId = searchParams.get("brandId");

  const where = {
    source: "ga4" as const,
    ...(targetBrandId ? { brandId: targetBrandId } : {}),
  };

  // Find all GA4 snapshots where conversions > sessions * 10
  const suspicious = await prisma.metricSnapshot.findMany({
    where,
    select: { id: true, brandId: true, date: true, sessions: true, conversions: true },
  });

  const toPurge = suspicious.filter(
    (s) => s.sessions > 10 && s.conversions > s.sessions * 3,
  );

  if (toPurge.length === 0) {
    return NextResponse.json({
      purged: 0,
      scanned: suspicious.length,
      message: "No suspicious GA4 conversion data found.",
    });
  }

  // Group by brand for logging
  const byBrand = new Map<string, number>();
  for (const row of toPurge) {
    byBrand.set(row.brandId, (byBrand.get(row.brandId) ?? 0) + 1);
  }

  // Zero out conversions but preserve sessions/users/pageViews
  const updated = await prisma.metricSnapshot.updateMany({
    where: { id: { in: toPurge.map((r) => r.id) } },
    data: { conversions: 0 },
  });

  const summary = Object.fromEntries(byBrand);
  console.info("[purge-ga4] Purged suspicious GA4 snapshots:", summary);

  return NextResponse.json({
    purged: updated.count,
    scanned: suspicious.length,
    byBrand: summary,
    sample: toPurge.slice(0, 5).map((r) => ({
      brandId: r.brandId,
      date: r.date.toISOString().split("T")[0],
      sessions: r.sessions,
      conversions: r.conversions,
      ratio: Math.round(r.conversions / r.sessions),
    })),
  });
}
