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

/**
 * Extracts the first two pages of a PDF and saves them as a new PDF file.
 * We do this instead of backend image conversion because Node Canvas fails 
 * compilation on Windows 10/Node 24 environments without Visual Studio. 
 * The client will smoothly render this secure 2-page PDF into an image via Canvas.
 */
async function extractFirstTwoPages(inputPath, outputPath) {
  try {
    const existingPdfBytes = fs.readFileSync(inputPath);
    const pdfDoc = await PDFDocument.load(existingPdfBytes);
    
    // Create a new document
    const newPdf = await PDFDocument.create();
    
    // Determine how many pages to copy (max 2)
    const pageCount = pdfDoc.getPageCount();
    const pagesToCopy = Math.min(pageCount, 2);
    
    const pageIndices = Array.from({ length: pagesToCopy }, (_, i) => i);
    
    if (pageIndices.length > 0) {
      const copiedPages = await newPdf.copyPages(pdfDoc, pageIndices);
      copiedPages.forEach((page) => newPdf.addPage(page));
    }
    
    const newPdfBytes = await newPdf.save();
    fs.writeFileSync(outputPath, newPdfBytes);
    
    return true;
  } catch (error) {
    console.error('Error processing PDF:', error);
    throw error;
  }
}

module.exports = {
  extractFirstTwoPages
};
