/**
 * GET /api/site-audit/[runId]/status
 * Returns run status + summary for polling.
 */
import { NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { verifyBrandAccess } from "@/lib/brand-access";

export const dynamic = "force-dynamic";

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ runId: string }> },
) {
  const { userId: clerkId } = await auth();
  if (!clerkId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { runId } = await params;

  const run = await prisma.siteAuditRun.findUnique({
    where: { id: runId },
    select: {
      id: true,
      status: true,
      score: true,
      subScores: true,
      categoryCounts: true,
      pagesScanned: true,
      pagesProcessed: true,
      issueCount: true,
      crawlError: true,
      errorMessage: true,
      llmsTxt: true,
      robotsTxt: true,
      robotsAiBlocks: true,
      sitemapFound: true,
      startedAt: true,
      completedAt: true,
      createdAt: true,
      brandId: true,
    },
  });

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

  // Resolve DB user by email (same path as the dashboard) so verifyBrandAccess
  // receives the DB User.id, not the Clerk user id.
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const allowed = await verifyBrandAccess(user.id, run.brandId);
  console.warn("[site-audit/status] access check", { clerkId, dbUserId: user.id, brandId: run.brandId, allowed });
  if (!allowed) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const { brandId: _b, ...data } = run;
  return NextResponse.json(data);
}
