/**
 * POST /api/admin/backfill-ai-referrals
 *
 * Scans existing TrackedSession records for AI platform referrers
 * (including Google AI Overview via text fragments in event metadata)
 * and creates AiAttribution records for any matches.
 *
 * Accepts either:
 *   - Authorization: Bearer $CRON_SECRET  (cron / scripts)
 *   - Authenticated superadmin session   (admin UI button)
 */

import { NextResponse } from "next/server";
import { runAiReferralBackfill, backfillMissingQueryContext } from "@/lib/services/ai-referral-backfill";
import { requireSuperadmin } from "@/lib/admin-auth";

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

export async function POST(req: Request) {
  const authHeader = req.headers.get("authorization");
  const cronSecret = process.env.CRON_SECRET;
  const hasValidCronAuth = cronSecret && authHeader === `Bearer ${cronSecret}`;

  if (!hasValidCronAuth) {
    const denied = await requireSuperadmin();
    if (denied) return denied;
  }

  const body = await req.json().catch(() => ({})) as { brandId?: string };
  const result = await runAiReferralBackfill(body.brandId ?? undefined);

  // Also patch any existing records that have null queryContext
  const queryContextPatched = await backfillMissingQueryContext().catch(() => 0);

  return NextResponse.json({ ...result, queryContextPatched });
}
