/**
 * GET /api/cron/cleanup-stale-audits
 *
 * Watchdog that marks any audit stuck in "running" status for more than
 * 14 minutes as failed. Runs every 2 minutes via Vercel Cron.
 *
 * A running audit whose updatedAt is > 14 minutes old indicates the
 * serverless function was killed (hit maxDuration) without cleaning up.
 * The 14-minute window gives buffer beyond the ~7-minute worst-case pipeline
 * (crawl ~4min + data/content/industry ~30s + synthesizer ~140s = ~7min).
 *
 * Protected by CRON_SECRET — Authorization: Bearer <secret> or ?secret=<secret>.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

const CRON_SECRET = process.env.CRON_SECRET ?? "";
const STALE_THRESHOLD_MS = 14 * 60 * 1000;

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

export async function GET(req: Request) {
  if (!isAuthorized(req)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const cutoff = new Date(Date.now() - STALE_THRESHOLD_MS);

  // Find audits stuck in running state beyond the stale threshold
  const staleAudits = await (prisma.audit.findMany as any)({
    where: {
      status: "running",
      updatedAt: { lt: cutoff },
    },
    select: { id: true },
  });

  if (staleAudits.length === 0) {
    console.log("[cron-cleanup] no stale audits found");
    return NextResponse.json({ cleaned: 0 });
  }

  const staleIds = (staleAudits as Array<{ id: string }>).map((a) => a.id);

  await (prisma.audit.updateMany as any)({
    where: { id: { in: staleIds } },
    data: {
      status: "failed",
      completedAt: new Date(),
      userFacingError:
        "This audit timed out before completing. Please retry — it usually succeeds on a second run.",
      errorReason: "function_timeout",
      errorDetail: "Watchdog cleanup",
    },
  });

  console.log(`[cron-cleanup] marked ${staleAudits.length} audits as failed: ${staleIds.join(", ")}`);

  return NextResponse.json({ cleaned: staleAudits.length, ids: staleIds });
}
