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

export async function OPTIONS(request: NextRequest) {
  return corsPreflight(request);
}

// Cross-Origin-Pendant zu /api/documents/[documentId]/pdf — die App kann den
// normalen Browser-Weg nicht nehmen (shell.openExternal hat keinen Zugriff
// auf die persist:rakku-team-Cookie-Jar), deshalb holt der Renderer die
// PDF-Bytes hier per fetch(credentials:"include") und öffnet sie lokal.
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }

  const { id } = await params;
  await connectDB();
  const [doc, settings] = await Promise.all([GeneratedDocument.findById(id).lean(), getSettings()]);
  if (!doc) return NextResponse.json({ error: "Nicht gefunden." }, { status: 404, headers });
  if (!(await hasPermission(documentCategoryPermission(doc.category, "view")))) {
    return NextResponse.json({ error: "Keine Berechtigung." }, { status: 401, headers });
  }

  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: { ...headers, "Content-Type": "application/pdf", "Cache-Control": "private, max-age=0, no-store" },
  });
}
