/**
 * POST /api/admin/cleanup-false-conversions
 *
 * Deletes SiteConversion records that were created by the false
 * phone_number_click detection (clicking near a phone number in the
 * header/footer triggering a conversion event).
 *
 * Body: { brandId?, dateFrom?, dateTo? }
 * Defaults: all brands, April 25-30 2026 (the spike window)
 */

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(req: Request) {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const body = await req.json().catch(() => ({})) as {
    brandId?: string;
    dateFrom?: string;
    dateTo?: string;
  };

  const where: Record<string, unknown> = {
    conversionType: { in: ["phone_call", "phone_number_click"] },
    detectionMethod: "phone_pattern",
  };

  if (body.brandId) where.brandId = body.brandId;

  const from = body.dateFrom ? new Date(body.dateFrom) : new Date("2026-04-25");
  const to = body.dateTo ? new Date(body.dateTo) : new Date("2026-04-30T23:59:59Z");
  where.timestamp = { gte: from, lte: to };

  // intentionally unfiltered: admin-only endpoint; needs raw or all-time counts
  const count = await prisma.siteConversion.count({ where }).catch(() => 0);

  const deleted = await prisma.siteConversion.deleteMany({ where }).catch(() => ({ count: 0 }));

  return NextResponse.json({
    found: count,
    deleted: deleted.count,
    dateRange: { from: from.toISOString(), to: to.toISOString() },
    brandId: body.brandId ?? "all",
  });
}
