import { getPreferredCustomerAddress } from "@/lib/customer-address";
import { getAccountSnapshot, getCustomerOrderById } from "@/lib/medusa/customer";
import { getInvoiceSettingsContent } from "@/lib/sanity/queries";
import { buildInvoicePdf } from "@/lib/invoice/pdf";
import { buildInvoiceNumber } from "@/lib/invoice/number";

type Context = {
  params: Promise<{ orderId: string }>;
};

export async function GET(_request: Request, context: Context) {
  const { orderId } = await context.params;
  const id = (orderId || "").trim();

  if (!id) {
    return Response.json({ error: "Order id is required." }, { status: 400 });
  }

  const order = await getCustomerOrderById(id);
  if (!order) {
    return Response.json({ error: "Order not found." }, { status: 404 });
  }

  const account = await getAccountSnapshot();
  const settings = await getInvoiceSettingsContent();
  const customerAddress = getPreferredCustomerAddress(account.addresses, order.shipping_address || null);
  const bytes = await buildInvoicePdf({ order, customerAddress, settings });
  const pdfBody = Uint8Array.from(bytes).buffer;
  const invoiceNumber = buildInvoiceNumber(order, settings);
  const filename = `facture-${invoiceNumber}.pdf`;

  return new Response(pdfBody, {
    status: 200,
    headers: {
      "Content-Type": "application/pdf",
      "Content-Disposition": `attachment; filename=\"${filename}\"`,
      "Cache-Control": "no-store",
    },
  });
}
