import { NextRequest, NextResponse } from "next/server";
import { ExcelLocale, generateDualSheetExcel } from "@/lib/export/excelGenerator";
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;
    }>(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 — die Mappe bekommt nie
    // ein leeres oder halb uebersetztes Beschriftungsset.
    const locale: ExcelLocale = body.locale === "en" ? "en" : "de";

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

    const excelBuffer = await generateDualSheetExcel(receipts, { locale });
    const dateStr = new Date().toISOString().split("T")[0];
    const filename =
      locale === "en" ? `Receipts_Export_${dateStr}.xlsx` : `Belege_Export_${dateStr}.xlsx`;

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