import { getPreferredCustomerAddress, type PdfCustomerAddress } from "@/lib/customer-address";
import { getAccountSnapshot } from "@/lib/medusa/customer";
import { getCustomerQuoteById } from "@/lib/medusa/quotes";
import { buildQuotePdf } from "@/lib/quote/pdf";
import { getQuoteSettingsContent } from "@/lib/sanity/queries";

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

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

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

  const account = await getAccountSnapshot();
  if (!account.authenticated || !account.customer) {
    return Response.json({ error: "Unauthorized." }, { status: 401 });
  }

  const quote = await getCustomerQuoteById(id, account);
  if (!quote) {
    return Response.json({ error: "Quote not found." }, { status: 404 });
  }

  const settings = await getQuoteSettingsContent();
  const fallbackAddress =
    quote.cart_snapshot && typeof quote.cart_snapshot === "object"
      ? (((quote.cart_snapshot as { shipping_address?: PdfCustomerAddress | null }).shipping_address || null) as PdfCustomerAddress | null)
      : null;
  const customerAddress = getPreferredCustomerAddress(account.addresses, fallbackAddress);
  const bytes = await buildQuotePdf({ quote, customerAddress, settings });
  const pdfBody = Uint8Array.from(bytes).buffer;
  const filename = `devis-${quote.reference || quote.id}.pdf`;

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