/**
 * GET /api/cron/dedup-conversions
 *
 * Hourly cron that runs the dedup engine for all active brands.
 * - Default hourly pass: lookbackDays=2 (recent data only, fast)
 * - Deep pass (03:00-04:00 UTC): lookbackDays=90 (catches older
 *   duplicates that accumulated before the cron was deployed)
 *
 * Schedule: "0 * * * *" (every hour)
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { runDedupForBrand } from "@/lib/conversions/run-dedup";
import { logCron } from "@/lib/services/cron-logger";

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

export async function GET(req: Request) {
  const cronSecret = process.env.CRON_SECRET;
  if (!cronSecret) {
    return NextResponse.json({ error: "Server misconfigured: CRON_SECRET unset" }, { status: 500 });
  }
  const authHeader = req.headers.get("authorization");
  const querySecret = new URL(req.url).searchParams.get("secret");
  if (authHeader !== `Bearer ${cronSecret}` && querySecret !== cronSecret) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  return logCron("/api/cron/dedup-conversions", async () => {
    const hour = new Date().getUTCHours();
    const isDeepPass = hour >= 3 && hour < 4;
    const lookbackDays = isDeepPass ? 90 : 2;

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

    const results: Array<{ brand: string; processed: number; marked: number; clusters: number; ms: number; error?: string }> = [];
    let totalMarked = 0;

    for (const brand of brands) {
      try {
        const r = await runDedupForBrand(brand.id, { lookbackDays });
        results.push({ brand: brand.name, processed: r.totalRowsProcessed, marked: r.duplicatesMarked, clusters: r.clustersFormed, ms: r.durationMs });
        totalMarked += r.duplicatesMarked;
      } catch (err) {
        results.push({ brand: brand.name, processed: 0, marked: 0, clusters: 0, ms: 0, error: err instanceof Error ? err.message : String(err) });
      }
    }

    const payload = {
      pass: isDeepPass ? "deep" : "hourly",
      lookbackDays,
      brands: brands.length,
      totalMarked,
      results,
    };
    return NextResponse.json(payload);
  });
}
