/**
 * GET /api/admin/audits/[id]/pdf
 * Streams a branded PDF for the given audit. Requires superadmin auth.
 * Query params:
 *   ?mode=executive   → 6-page Executive Brief PDF
 *   ?mode=comprehensive (default) → full 40-50 page audit PDF
 */

import { requireSuperadmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";
import { renderToBuffer } from "@react-pdf/renderer";
import { createElement } from "react";
import { AuditPdf } from "@/lib/audit/pdf/AuditPdf";
import { ExecutiveAuditPdf } from "@/lib/audit/pdf/ExecutiveAuditPdf";
import type { SeoSection } from "@/lib/audit/types";

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

function slugify(s: string): string {
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
}

export async function GET(
  req: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const { id } = await params;
  const url = new URL(req.url);
  const mode = url.searchParams.get("mode") === "executive" ? "executive" : "comprehensive";

  const audit = await prisma.audit.findUnique({
    where: { id },
    select: {
      id: true,
      requestedBrandName: true,
      requestedWebsite: true,
      completedAt: true,
      status: true,
      seoSection: true,
      rawData: true,
      brandId: true,
      siteTagDetected: true,
    },
  }).catch(() => null);

  if (!audit) return new Response("Audit not found", { status: 404 });
  if (audit.status !== "completed" || !audit.seoSection) {
    return new Response("Audit not yet complete", { status: 409 });
  }

  const seo = audit.seoSection as unknown as SeoSection;

  if (mode === "executive" && !seo.executiveBrief) {
    return new Response(
      "Executive Brief not available for this audit. Use ?mode=comprehensive instead.",
      { status: 400 },
    );
  }

  const brandName = seo.brandEcho?.brandName ?? audit.requestedBrandName ?? "Unknown";
  const website = audit.requestedWebsite ?? "";
  const auditDate = audit.completedAt
    ? new Date(audit.completedAt).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })
    : new Date().toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" });
  const isFirstParty = !!audit.brandId && !!(audit.siteTagDetected || (audit.seoSection as Record<string, unknown> | null)?.aiSearchPerformance);

  let element: ReturnType<typeof createElement>;
  let filename: string;

  if (mode === "executive") {
    const comprehensiveUrl = `${url.origin}/admin/audits/${id}?view=full`;
    element = createElement(ExecutiveAuditPdf, {
      brandName,
      website,
      auditDate,
      auditId: id,
      isFirstParty,
      seo,
      comprehensiveAuditUrl: comprehensiveUrl,
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    }) as any;
    filename = `${slugify(brandName)}-executive-brief-${new Date().toISOString().slice(0, 10)}.pdf`;
  } else {
    element = createElement(AuditPdf, {
      brandName,
      website,
      auditDate,
      auditId: id,
      isFirstParty,
      seo,
      rawData: audit.rawData as Record<string, unknown> | null,
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    }) as any;
    filename = `${slugify(brandName)}-audit-${new Date().toISOString().slice(0, 10)}.pdf`;
  }

  const buffer = await renderToBuffer(element);

  // Track download
  prisma.platformEvent.create({
    data: {
      userId: null,
      brandId: audit.brandId ?? null,
      action: "audit.pdf_downloaded",
      category: "audit",
      metadata: { auditType: "admin", auditId: id, pdfMode: mode },
    },
  }).catch(() => {/* non-fatal */});

  return new Response(new Uint8Array(buffer), {
    headers: {
      "Content-Type": "application/pdf",
      "Content-Disposition": `attachment; filename="${filename}"`,
      "Cache-Control": "private, max-age=300",
    },
  });
}
