import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { connectDB } from "@/lib/db";
import { Invoice } from "@/models/Invoice";
import { Client } from "@/models/Client";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, hasPermission } from "@/lib/adminAuth";
import { renderInvoicePdf } from "@/lib/invoicePdf";
import { embedZugferd } from "@/lib/zugferd";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

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

export async function GET(request: NextRequest, { params }: { params: Promise<{ invoiceId: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession()) || !(await hasPermission("invoicing"))) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }

  const { invoiceId } = await params;
  await connectDB();
  const invoice = await Invoice.findById(invoiceId).lean();
  if (!invoice) return NextResponse.json({ error: "Nicht gefunden." }, { status: 404, headers });

  const invoiceClient = await Client.findById(invoice.clientId).select("locale").lean();
  const locale = invoiceClient?.locale === "en" ? "en" : "de";

  const basePdf = await renderInvoicePdf(invoice, locale);
  let finalPdf: Uint8Array = new Uint8Array(basePdf);
  try {
    finalPdf = await embedZugferd(finalPdf, invoice);
  } catch (err) {
    console.error("ZUGFeRD-Einbettung fehlgeschlagen, liefere normale PDF-Rechnung:", err);
  }

  return new NextResponse(Buffer.from(finalPdf), { headers: { ...headers, "Content-Type": "application/pdf", "Cache-Control": "private, max-age=0, no-store" } });
}
