/**
 * GET /api/admin/audits/[id]/status
 *
 * Lightweight polling endpoint for the progress UI.
 * Returns only the fields needed to render live step progress.
 */

import { NextResponse } from "next/server";
import { requireSuperadmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const { id } = await params;

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const audit = await (prisma.audit.findUnique as any)({
    where: { id },
    select: {
      status: true,
      auditMode: true,
      progressStep: true,
      progressLabel: true,
      progressDetail: true,
      siteTagDetected: true,
      startedAt: true,
    },
  }).catch(() => null);

  if (!audit) {
    return NextResponse.json({ error: "Audit not found" }, { status: 404 });
  }

  const elapsedSeconds = audit.startedAt
    ? Math.round((Date.now() - new Date(audit.startedAt).getTime()) / 1000)
    : 0;

  return NextResponse.json({
    status: audit.status,
    auditMode: audit.auditMode ?? "auto",
    progressStep: audit.progressStep ?? 0,
    progressLabel: audit.progressLabel ?? null,
    progressDetail: audit.progressDetail ?? null,
    siteTagDetected: audit.siteTagDetected ?? null,
    elapsedSeconds,
  });
}
