/**
 * GET /api/public-audit/[id]/pdf
 * Streams a branded PDF for a completed public audit. No auth required.
 * Rate-limited to 5 downloads per audit ID to prevent abuse.
 * Query params:
 *   ?mode=executive   → 6-page Executive Brief PDF
 *   ?mode=comprehensive (default) → full audit PDF
 */

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 = 60;

// In-memory rate limit: max 5 downloads per auditId per cold start
const dlCount = new Map<string, number>();
const DL_MAX = 5;

function checkDownloadLimit(auditId: string): boolean {
  const n = (dlCount.get(auditId) ?? 0) + 1;
  dlCount.set(auditId, n);
  return n <= DL_MAX;
}

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 { id } = await params;
  const url = new URL(req.url);
  const mode = url.searchParams.get("mode") === "executive" ? "executive" : "comprehensive";

  if (!checkDownloadLimit(id)) {
    return new Response("Too many downloads for this audit", { status: 429 });
  }

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

  if (!audit) return new Response("Audit not found", { status: 404 });
  if (audit.source !== "public") return new Response("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 ?? "Your Site";
  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" });

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

  if (mode === "executive") {
    element = createElement(ExecutiveAuditPdf, {
      brandName,
      website,
      auditDate,
      auditId: id,
      isFirstParty: false,
      seo,
    // 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: false,
      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: null,
      action: "audit.pdf_downloaded",
      category: "audit",
      metadata: { auditType: "public", 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",
    },
  });
}
