/**
 * GET /api/site-audit/latest?brandId=X
 * Returns the most recent SiteAuditRun (any status) for a brand.
 */
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) {
  const { userId: clerkId } = await auth();
  if (!clerkId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const brandId = new URL(req.url).searchParams.get("brandId") ?? "";
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  // 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, brandId);
  console.warn("[site-audit/latest] access check", { clerkId, dbUserId: user.id, brandId, allowed });
  if (!allowed) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const run = await prisma.siteAuditRun.findFirst({
    where: { brandId },
    orderBy: { createdAt: "desc" },
    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,
      sitemapUrl: true,
      startedAt: true,
      completedAt: true,
      createdAt: true,
    },
  });

  if (!run) return NextResponse.json({ run: null });
  return NextResponse.json({ run });
}
