const { PDFDocument } = require('pdf-lib');
const fs = require('fs').promises;

class PDFProcessor {
    /**
     * Split a PDF document into multiple documents based on page count
     * @param {Buffer} inputBuffer - Buffer containing the input PDF file
     * @param {number} pagesPerDoc - Number of pages per output document
     * @param {Array} metadata - Array of metadata objects for naming output files
     * @returns {Promise<Array>} Array of objects containing filename and buffer for each PDF
     */
    async splitPDF(inputBuffer, pagesPerDoc, metadata) {
        try {
            // Load the PDF from buffer
            const pdfDoc = await PDFDocument.load(inputBuffer);
            const totalPages = pdfDoc.getPageCount();

            // Calculate number of output documents
            const numDocs = Math.ceil(totalPages / pagesPerDoc);
            const outputFiles = [];

            // Validate metadata array length matches number of output documents
            if (metadata.length < numDocs) {
                throw new Error('Insufficient metadata provided for number of output documents');
            }

            // Process each chunk of pages
            for (let i = 0; i < numDocs; i++) {
                const startPage = i * pagesPerDoc;
                const endPage = Math.min((i + 1) * pagesPerDoc, totalPages);
                
                // Create a new PDF document
                const newPdfDoc = await PDFDocument.create();
                
                // Copy pages from original document
                const pages = await newPdfDoc.copyPages(pdfDoc, Array.from(
                    { length: endPage - startPage }, 
                    (_, index) => startPage + index
                ));
                
                // Add pages to new document
                pages.forEach(page => newPdfDoc.addPage(page));
                
                // Generate filename from metadata
                const { name, lastname } = metadata[i];
                const filename = `${name.toLowerCase()}_${lastname.toLowerCase()}.pdf`;
                
                // Save the new PDF to buffer
                const newPdfBuffer = await newPdfDoc.save();
                
                outputFiles.push({
                    filename,
                    buffer: newPdfBuffer
                });
            }

            return outputFiles;
        } catch (error) {
            throw new Error(`PDF processing failed: ${error.message}`);
        }
    }
}

module.exports = new PDFProcessor();