import { NextRequest, NextResponse } from "next/server";
import { PdfLocale, generateReceiptPdf } from "@/lib/export/pdfGenerator";
import { ProcessedReceipt } from "@/lib/schema/receipt";
import { MAX_JSON_BODY_BYTES } from "@/lib/limits";
import { readJsonSized } from "@/lib/http/requestSize";
import { requireCsrf } from "@/lib/auth/csrf";
import { requireProExporter } from "@/lib/export/access";

export const runtime = "nodejs";

export async function POST(req: NextRequest) {
  try {
    const csrfBlocked = requireCsrf(req);
    if (csrfBlocked) return csrfBlocked;
    const gate = await requireProExporter(req);
    if (!gate.ok) return gate.response;

    const parsed = await readJsonSized<{
      receipts?: ProcessedReceipt[];
      locale?: string;
      dateFrom?: string;
      dateTo?: string;
    }>(req, MAX_JSON_BODY_BYTES);
    if (!parsed.ok) return parsed.response;
    const body = parsed.body;
    const receipts: ProcessedReceipt[] = body.receipts || [];
    // Unbekannte Werte fallen auf Deutsch zurueck.
    const locale: PdfLocale = body.locale === "en" ? "en" : "de";
    const dateFrom: string | undefined = typeof body.dateFrom === "string" ? body.dateFrom : undefined;
    const dateTo: string | undefined = typeof body.dateTo === "string" ? body.dateTo : undefined;

    if (!receipts || receipts.length === 0) {
      return NextResponse.json(
        { error: locale === "en" ? "No receipts to export" : "Keine Belege zum Exportieren vorhanden" },
        { status: 400 }
      );
    }

    const pdfBytes = await generateReceiptPdf(receipts, { locale, dateFrom, dateTo });
    const dateStr = new Date().toISOString().split("T")[0];
    const filename =
      locale === "en" ? `Receipts_Export_${dateStr}.pdf` : `Belege_Export_${dateStr}.pdf`;

    return new NextResponse(new Uint8Array(pdfBytes), {
      status: 200,
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": `attachment; filename="${filename}"`,
        "Content-Length": pdfBytes.length.toString(),
      },
    });
  } catch (error: any) {
    console.error("PDF export error:", error);
    return NextResponse.json(
      { error: error?.message || "Fehler beim Erstellen der PDF-Datei" },
      { status: 500 }
    );
  }
}