/**
 * POST /api/content-audit/run — Run content audit for a brand.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { auditContent } from "@/lib/services/content-auditor";

export const dynamic = "force-dynamic";
export const maxDuration = 120;

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json().catch(() => null);
  if (!body?.brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  try {
    const result = await auditContent(body.brandId);
    const saved = await prisma.contentAuditResult.create({
      data: { brandId: body.brandId, totalPages: result.totalPages, results: JSON.parse(JSON.stringify(result.results)), aiSummary: result.aiSummary },
    });
    return NextResponse.json({ ...result, id: saved.id });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Audit failed" }, { status: 500 });
  }
}
