// Open the browser's print dialog for a PDF file (e.g. an uploaded document).
//
// The file lives on the API origin, so we cannot print it from an iframe
// directly (cross-origin). Instead we download it as a blob — blob URLs belong
// to our own origin — load that into a hidden iframe, and call print() on it.
// The result is the native print dialog previewing the PDF's own pages.
export async function printPdfFromUrl(url: string): Promise<void> {
  try {
    const response = await fetch(url, { credentials: "include" });

    if (!response.ok) {
      throw new Error(`Failed to load PDF (status ${response.status})`);
    }

    const blob = await response.blob();
    const blobUrl = URL.createObjectURL(blob);

    // A zero-size iframe (not display:none — some browsers refuse to print
    // fully hidden frames) that hosts the PDF for printing.
    const iframe = document.createElement("iframe");
    iframe.style.position = "fixed";
    iframe.style.right = "0";
    iframe.style.bottom = "0";
    iframe.style.width = "0";
    iframe.style.height = "0";
    iframe.style.border = "0";
    iframe.src = blobUrl;

    iframe.onload = () => {
      iframe.contentWindow?.focus();
      iframe.contentWindow?.print();
    };

    document.body.appendChild(iframe);

    // Clean up long after the print dialog has been dealt with.
    window.setTimeout(() => {
      URL.revokeObjectURL(blobUrl);
      iframe.remove();
    }, 60_000);
  } catch {
    // Fallback: open the PDF in a new tab; the viewer there can print it.
    window.open(url, "_blank", "noopener");
  }
}
