import { NextResponse } from "next/server";
import { getSessionCustomer, getCustomerOrderDetail } from "../../../../../lib/customerAuth";
import { generateCorrectionInvoicePdf, getSellerForInvoice } from "../../../../../lib/invoiceData";
import { getProductImagesByIds } from "../../../../../lib/payload";

// On-demand download for "Stornorechnung/Gutschrift herunterladen" on
// /konto/bestellungen/[orderNumber]. The real document was generated once
// by Payload's Orders.ts afterChange hook and emailed at the moment of the
// status change — this regenerates the identical PDF from the order's own
// stored correctionInvoiceNumber/correctionInvoiceIssuedAt (immutable once
// set) rather than storing the file anywhere, same approach as the
// original invoice's own download route.
export async function GET(request: Request, { params }: { params: Promise<{ orderNumber: string }> }) {
  const session = await getSessionCustomer();
  if (!session) return NextResponse.json({ ok: false, reason: "Bitte zuerst einloggen." }, { status: 401 });

  const { orderNumber } = await params;
  const order = await getCustomerOrderDetail(session.token, session.customer.id, decodeURIComponent(orderNumber));
  if (!order) return NextResponse.json({ ok: false, reason: "Bestellung nicht gefunden." }, { status: 404 });
  if (!order.correctionInvoiceNumber || !order.correctionInvoiceIssuedAt || !order.invoiceNumber || !order.invoiceIssuedAt) {
    return NextResponse.json({ ok: false, reason: "Für diese Bestellung liegt keine Korrekturrechnung vor." }, { status: 404 });
  }
  const kind = order.status === "returned" ? "gutschrift" : "storno";

  const seller = await getSellerForInvoice();
  const imagesByProductId = await getProductImagesByIds(order.items.map((item) => item.product));
  const pdf = await generateCorrectionInvoicePdf(
    kind,
    {
      orderNumber: order.orderNumber,
      invoiceNumber: order.invoiceNumber,
      invoiceIssuedAt: order.invoiceIssuedAt,
      correctionInvoiceNumber: order.correctionInvoiceNumber,
      correctionInvoiceIssuedAt: order.correctionInvoiceIssuedAt,
      customerFirstName: order.customerFirstName,
      customerLastName: order.customerLastName,
      companyName: order.companyName,
      vatId: order.vatId,
      vatExempt: order.vatExempt,
      kleinunternehmer: order.kleinunternehmer,
      deliveryMethod: order.deliveryMethod,
      street: order.street,
      packstationNumber: order.packstationNumber,
      postNumber: order.postNumber,
      zip: order.zip,
      city: order.city,
      country: order.country,
      items: order.items.map((item) => ({ ...item, imageUrl: imagesByProductId.get(item.product) ?? null })),
      subtotal: order.subtotal,
      shippingCost: order.shippingCost,
      discountAmount: order.discountAmount,
      total: order.total,
    },
    seller,
  );
  if (!pdf) return NextResponse.json({ ok: false, reason: "Korrekturrechnung konnte nicht erzeugt werden." }, { status: 500 });

  const filename = kind === "storno" ? `Stornorechnung-${order.correctionInvoiceNumber}.pdf` : `Gutschrift-${order.correctionInvoiceNumber}.pdf`;
  return new NextResponse(new Uint8Array(pdf), {
    status: 200,
    headers: {
      "Content-Type": "application/pdf",
      "Content-Disposition": `attachment; filename="${filename}"`,
    },
  });
}
