/**
 * POST /api/admin/cleanup-snapshots
 *
 * Finds MetricSnapshot duplicates (same brandId + date but different
 * source) where one row has data and another is all zeros. Deletes
 * the zero rows. Also purges known-corrupt rows where conversions >
 * sessions × 5.
 *
 * The @@unique([brandId, date, source]) constraint allows multiple
 * rows per brand+date when source differs ("ga4" vs "seed" vs "daily").
 * The chart's buildDailyTrendFromSnapshots aggregates all sources per
 * date, so a zero row from an old "seed" import inflates nothing but
 * visually confuses when the debug endpoint shows "two rows for Apr 12".
 */

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

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

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

  // 1. Find brand+date combos with multiple rows
  type DupRow = { brandId: string; date: Date; cnt: bigint };
  const duplicates = await prisma.$queryRaw<DupRow[]>`
    SELECT "brandId", date, COUNT(*) as cnt
    FROM "MetricSnapshot"
    GROUP BY "brandId", date
    HAVING COUNT(*) > 1
  `.catch(() => []);

  let zeroRowsDeleted = 0;
  let corruptRowsDeleted = 0;

  // For each duplicate set, delete zero rows (keep the one with most data)
  for (const dup of duplicates) {
    const rows = await prisma.metricSnapshot.findMany({
      where: { brandId: dup.brandId, date: dup.date },
      orderBy: { sessions: "desc" },
    });

    if (rows.length <= 1) continue;

    // Keep the row with the highest sessions count; delete zero rows
    for (let i = 1; i < rows.length; i++) {
      const r = rows[i];
      if (r.sessions === 0 && r.conversions === 0 && r.users === 0) {
        await prisma.metricSnapshot.delete({ where: { id: r.id } }).catch(() => null);
        zeroRowsDeleted++;
      }
    }
  }

  // 2. Purge corrupt rows where conversions > sessions × 5
  corruptRowsDeleted = await prisma.$executeRaw`
    DELETE FROM "MetricSnapshot"
    WHERE "sessions" > 0 AND "conversions" > "sessions" * 5
  `.catch(() => 0);

  return NextResponse.json({
    duplicateSets: duplicates.length,
    zeroRowsDeleted,
    corruptRowsDeleted,
  });
}
