import { NextRequest, NextResponse } from "next/server";
import { connectDB } from "@/lib/db";
import { GeneratedDocument } from "@/models/GeneratedDocument";
import { Client } from "@/models/Client";
import { hasPermission } from "@/lib/adminAuth";
import { renderDocumentPdf } from "@/lib/documentPdf";
import { getSettings } from "@/lib/settings";
import { documentCategoryPermission } from "@/lib/documentConstants";
import { formatDateDE } from "@/lib/orderConstants";

// HTTP-Header dürfen nur ASCII/Latin-1 enthalten — Umlaute, Gedankenstriche
// (–) o. Ä. im Dokumenttitel würden die Response sonst mit einer
// "ByteString"-TypeError zum Absturz bringen. ASCII-Fallback + RFC-5987
// UTF-8-Variante für Browser, die den echten Dateinamen anzeigen können.
function contentDispositionFilename(name: string): string {
  const ascii = name.replace(/[^\x20-\x7E]/g, "_");
  const utf8 = encodeURIComponent(name);
  return `inline; filename="${ascii}.pdf"; filename*=UTF-8''${utf8}.pdf`;
}

export async function GET(_req: NextRequest, { params }: { params: Promise<{ documentId: string }> }) {
  const { documentId } = await params;
  await connectDB();
  const [doc, settings] = await Promise.all([GeneratedDocument.findById(documentId).lean(), getSettings()]);
  if (!doc) return new NextResponse("Not found", { status: 404 });
  if (!(await hasPermission(documentCategoryPermission(doc.category, "view")))) return new NextResponse("Unauthorized", { status: 401 });

  const inv = settings.invoiceSettings;
  const businessName = inv?.businessName || "Rakku Photography";
  const createdBy = doc.createdBy ? await Client.findById(doc.createdBy).select("name").lean() : null;

  const buffer = await renderDocumentPdf({
    letterhead: doc.includeLetterhead
      ? {
          businessName,
          legalName: inv?.legalName || "",
          street: inv?.street || "",
          postCode: inv?.postCode || "",
          city: inv?.city || "",
          countryCode: inv?.countryCode || "DE",
        }
      : null,
    recipient: doc.includeRecipientAddress && doc.recipientAddress ? { name: doc.clientName, address: doc.recipientAddress } : null,
    employeeName: doc.clientName || "",
    createdByName: createdBy?.name || "",
    contactEmail: settings.socialLinks?.email || "contact@rakku.de",
    website: "rakku.de",
    templateName: doc.templateName,
    category: doc.category,
    renderedBody: doc.renderedBody,
    footerText: doc.includeFooter
      ? doc.footerText || `Erstellt am ${formatDateDE(new Date(doc.createdAt))} · ${businessName}`
      : null,
    generatedAt: new Date(doc.createdAt),
    signature: doc.signature ? { name: doc.signature.name, signedAt: new Date(doc.signature.signedAt) } : null,
  });

  return new NextResponse(new Uint8Array(buffer), {
    headers: {
      "Content-Type": "application/pdf",
      "Content-Disposition": contentDispositionFilename(`${doc.templateName}-${doc.clientName || documentId}`),
      "Cache-Control": "private, max-age=0, no-store",
    },
  });
}
