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

// On-demand download for "Rechnung herunterladen" on
// /konto/bestellungen/[orderNumber] — reuses the exact same render call as
// the checkout-time attachment (app/lib/orderEmail.ts), so a re-download
// always matches what was emailed; invoiceNumber itself never changes
// (assigned once, server-side, at order creation — see Orders.ts).
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.invoiceNumber || !order.invoiceIssuedAt) {
    return NextResponse.json({ ok: false, reason: "Für diese Bestellung liegt noch keine Rechnung vor." }, { status: 404 });
  }

  const seller = await getSellerForInvoice();
  // On-demand re-download has no imageUrl snapshot to fall back to like
  // the checkout-time attachment does (order.items only stores a numeric
  // product id, see CustomerOrderItem) — resolved fresh here instead.
  const imagesByProductId = await getProductImagesByIds(order.items.map((item) => item.product));
  const pdf = await generateInvoicePdf(
    {
      orderNumber: order.orderNumber,
      invoiceNumber: order.invoiceNumber,
      invoiceIssuedAt: order.invoiceIssuedAt,
      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,
      hasDifferentShippingAddress: order.hasDifferentShippingAddress,
      shippingFirstName: order.shippingFirstName,
      shippingLastName: order.shippingLastName,
      shippingDeliveryMethod: order.shippingDeliveryMethod,
      shippingStreet: order.shippingStreet,
      shippingPackstationNumber: order.shippingPackstationNumber,
      shippingPostNumber: order.shippingPostNumber,
      shippingZip: order.shippingZip,
      shippingCity: order.shippingCity,
      shippingCountry: order.shippingCountry,
      paymentMethodTitle: order.paymentMethodTitle,
      items: order.items.map((item) => ({ ...item, imageUrl: imagesByProductId.get(item.product) ?? null })),
      subtotal: order.subtotal,
      shippingCost: order.shippingCost,
      discountAmount: order.discountAmount,
      discountCode: order.discountCode,
      total: order.total,
    },
    seller,
  );
  if (!pdf) return NextResponse.json({ ok: false, reason: "Rechnung konnte nicht erzeugt werden." }, { status: 500 });

  return new NextResponse(new Uint8Array(pdf), {
    status: 200,
    headers: {
      "Content-Type": "application/pdf",
      "Content-Disposition": `attachment; filename="Rechnung-${order.invoiceNumber}.pdf"`,
    },
  });
}
