/**
 * POST /api/technical-audit/run
 * Body: { brandId }
 * Triggers a technical audit for a brand.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { runTechnicalAudit } from "@/lib/services/audit-runner";

export const dynamic = "force-dynamic";
// Full-fidelity audit pipeline (crawl + SERP + all synthesizers + visual annotation).
// Matches the 800s budget used by admin/audits/trigger and public-audit routes.
export const maxDuration = 800;

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

    let body: Record<string, unknown>;
    try {
      body = await req.json();
    } catch {
      return NextResponse.json({ error: "Invalid request body" }, { status: 400 });
    }

    const brandId = body.brandId as string;
    if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

    const brand = await prisma.brand.findUnique({
      where: { id: brandId },
      include: { organization: { include: { memberships: true } } },
    });
    if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
    if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
      return NextResponse.json({ error: "Access denied" }, { status: 403 });
    }

    const result = await runTechnicalAudit(brandId, brand.domain);

    // Save audit score history (fire-and-forget)
    if (result.status === "completed" && result.crawlHealth != null) {
      const r = result as unknown as Record<string, number>;
      prisma.auditScoreHistory.create({
        data: {
          brandId,
          healthScore: Math.round(result.crawlHealth),
          errorCount: r.errorCount ?? 0,
          warningCount: r.warningCount ?? 0,
          infoCount: r.infoCount ?? 0,
          totalIssues: r.issues ?? 0,
        },
      }).catch(() => {});
    }

    return NextResponse.json(result);
  } catch (err) {
    const message = err instanceof Error ? err.message : "An unexpected error occurred";
    return NextResponse.json(
      { status: "failed", auditId: null, crawlHealth: 0, issues: 0, message },
      { status: 500 }
    );
  }
}
