/**
 * GET /api/public-audit/[id] — public audit status polling endpoint.
 *
 * Returns safe subset of audit fields (no internal admin data).
 * No auth required — auditId is a CUID and unguessable.
 */

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

export const dynamic = "force-dynamic";

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

  const audit = await prisma.audit.findUnique({
    where: { id },
    select: {
      id: true,
      status: true,
      requestedWebsite: true,
      currentTier: true,
      totalTiers: true,
      currentTierLabel: true,
      tiersCompleted: true,
      estimatedSecondsRemaining: true,
      seoSection: true,
      rawData: true,
      userFacingError: true,
      completedAt: true,
    },
  }).catch(() => null);

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

  // Only serve public-sourced audits through this endpoint.
  // Prisma type doesn't include `source` until next generate; cast is safe
  // because the schema field exists and the DB default is "admin".
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const auditSource = (audit as any).source as string | undefined;
  if (auditSource && auditSource !== "public") {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  return NextResponse.json({ audit });
}
