/**
 * POST /api/site-audit/[runId]/process
 *
 * Internal-only cron re-kick endpoint. Auth: CRON_SECRET Bearer token.
 * The initial kick from /api/site-audit/run calls runSiteAudit() directly
 * via waitUntil -- this route exists only for the cleanup cron to re-kick
 * runs that were interrupted mid-crawl.
 */
import { NextResponse } from "next/server";
import { runSiteAudit } from "@/lib/services/site-audit-runner";

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

const CRON_SECRET = process.env.CRON_SECRET ?? "";

function isAuthorized(req: Request): boolean {
  if (!CRON_SECRET) return false;
  const header = req.headers.get("authorization") ?? "";
  if (header === `Bearer ${CRON_SECRET}`) return true;
  return new URL(req.url).searchParams.get("secret") === CRON_SECRET;
}

export async function POST(
  req: Request,
  { params }: { params: Promise<{ runId: string }> },
) {
  if (!isAuthorized(req)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { runId } = await params;

  try {
    await runSiteAudit(runId);
    return NextResponse.json({ ok: true, runId });
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    return NextResponse.json({ ok: false, error: msg }, { status: 500 });
  }
}
