/**
 * POST /api/admin/audits/[id]/retry
 * Creates a new audit with the same parameters as the source audit
 * and fires the runner asynchronously. Requires superadmin auth.
 */

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,
  { params }: { params: Promise<{ id: string }> },
) {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const { id } = await params;

  const source = await prisma.audit.findUnique({
    where: { id },
    select: {
      brandId: true,
      requesterEmail: true,
      requestedBrandName: true,
      requestedWebsite: true,
      requestedCompetitors: true,
      requestedLocations: true,
      requestedServices: true,
      isLocal: true,
      auditType: true,
      auditMode: true,
      source: true,
    },
  }).catch(() => null);

  if (!source) return NextResponse.json({ error: "Audit not found" }, { status: 404 });
  if (!source.requestedWebsite) return NextResponse.json({ error: "Source audit has no website" }, { status: 422 });

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

  console.log(`[audit-retry] source=${id} new=${newAudit.id}`);

  waitUntil(
    runAudit(newAudit.id).catch((e: unknown) =>
      console.error(`[audit-retry] runner failed for ${newAudit.id}:`, e instanceof Error ? e.message : e),
    ),
  );

  return NextResponse.json({ newAuditId: newAudit.id, status: "queued" }, { status: 202 });
}
