import { NextRequest, NextResponse } from "next/server";
import { CsvLocale, generateAccountingCsv } from "@/lib/export/csvGenerator";
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 || [];
    const locale: CsvLocale = 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 }
      );
    }

    // CSV-Export (UTF-8 mit BOM, Semikolon). Ein importierbarer
    // Reine Datentabelle – bewusst ohne Buchungslogik.
    const csvContent = generateAccountingCsv(receipts, { locale });
    const dateStr = new Date().toISOString().split("T")[0];
    const filename =
      locale === "en" ? `Receipts_Export_${dateStr}.csv` : `Belege_Export_${dateStr}.csv`;

    return new NextResponse(csvContent, {
      status: 200,
      headers: {
        "Content-Type": "text/csv; charset=utf-8",
        "Content-Disposition": `attachment; filename="${filename}"`,
      },
    });
  } catch (error: any) {
    console.error("CSV export error:", error);
    return NextResponse.json(
      { error: error?.message || "Fehler beim Erstellen der CSV-Datei" },
      { status: 500 }
    );
  }
}
