import { PDFDocument } from 'pdf-lib';

/**
 * Merges a list of PDF blobs/files into a single PDF document.
 * Can handle mixing base report buffers with attachment files.
 * 
 * @param {ArrayBuffer} baseReportBuffer - The main report content (optional)
 * @param {Array} attachments - Array of attachment objects { file: File|Blob, url: string, ... }
 * @returns {Promise<Uint8Array>} - The combined PDF bytes
 */
export const mergePDFs = async (baseReportBuffer, attachments = []) => {
  try {
    const mergedPdf = await PDFDocument.create();

    // 1. Add Base Report (if provided)
    if (baseReportBuffer) {
        try {
            const basePdf = await PDFDocument.load(baseReportBuffer);
            const copiedPages = await mergedPdf.copyPages(basePdf, basePdf.getPageIndices());
            copiedPages.forEach((page) => mergedPdf.addPage(page));
        } catch (e) {
            console.error("Failed to load base report PDF", e);
            throw new Error("Base report generation failed.");
        }
    }

    // 2. Add Attachments
    for (const item of attachments) {
        let fileBuffer;
        
        try {
            // Handle different sources (File object, URL, or ArrayBuffer)
            if (item.file instanceof ArrayBuffer) {
                fileBuffer = item.file;
            } else if (item.file instanceof Blob) {
                fileBuffer = await item.file.arrayBuffer();
            } else if (item.url) {
                // Fetch from URL
                const response = await fetch(item.url);
                if (!response.ok) throw new Error(`Failed to fetch PDF from ${item.url}`);
                fileBuffer = await response.arrayBuffer();
            } else {
                console.warn(`Skipping invalid attachment: ${item.name}`);
                continue;
            }

            const pdfDoc = await PDFDocument.load(fileBuffer);
            const copiedPages = await mergedPdf.copyPages(pdfDoc, pdfDoc.getPageIndices());
            copiedPages.forEach((page) => mergedPdf.addPage(page));
        } catch (e) {
            console.error(`Failed to merge PDF attachment: ${item.name}`, e);
            // We skip invalid files but continue the merge process
        }
    }

    return await mergedPdf.save();
  } catch (error) {
    console.error("PDF Merge Utility Error:", error);
    throw new Error("Failed to merge PDF files. Please verify all attachments are valid PDF documents.");
  }
};