/**
 * POST /api/admin/audits/trigger
 *
 * Creates a new Audit record and fires the runner in the background.
 * Returns immediately with the auditId so the caller can poll for progress.
 */

import { NextResponse } from "next/server";
import { waitUntil } from "@vercel/functions";
import { requireSuperadmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";
import { runAudit } from "@/lib/audit/audit-runner";

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

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

  let body: {
    brandName?: string;
    website?: string;
    competitors?: string[];
    locations?: string[];
    services?: string[];
    isLocal?: boolean;
    requesterEmail?: string;
    brandId?: string;
    auditMode?: string;
  };

  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }

  if (!body.website) {
    return NextResponse.json({ error: "website is required" }, { status: 400 });
  }

  // Normalise website URL
  let website = body.website.trim();
  if (!website.startsWith("http")) website = `https://${website}`;

  const validModes = ["auto", "first-party", "third-party"];
  const auditMode = validModes.includes(body.auditMode ?? "") ? body.auditMode! : "auto";

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const audit = await (prisma.audit.create as any)({
    data: {
      brandId: body.brandId ?? null,
      requesterEmail: body.requesterEmail ?? null,
      requestedBrandName: body.brandName ?? null,
      requestedWebsite: website,
      requestedCompetitors: body.competitors ?? [],
      requestedLocations: body.locations ?? [],
      requestedServices: body.services ?? [],
      isLocal: body.isLocal ?? false,
      auditType: body.brandId ? "first-party" : "third-party",
      auditMode,
      status: "queued",
      currentTier: 0,
      totalTiers: 7,
    },
  });

  // Keep function alive until runner completes (or maxDuration is hit)
  waitUntil(runAudit(audit.id));

  return NextResponse.json({ auditId: audit.id });
}