const puppeteer = require('puppeteer');
const path = require('path');

class InvoicePDFGenerator {
    constructor() {
        this.browser = null;
        this.page = null;
    }

    async init() {
        this.browser = await puppeteer.launch({
            headless: true,
            args: [
                '--no-sandbox',
                '--disable-setuid-sandbox',
                '--disable-dev-shm-usage',
                '--disable-accelerated-2d-canvas',
                '--no-first-run',
                '--no-zygote',
                '--single-process',
                '--disable-gpu'
            ]
        });
        this.page = await this.browser.newPage();
    }

    async generatePDF(htmlContent, outputPath, options = {}) {
        try {
            await this.page.setContent(htmlContent, { waitUntil: 'networkidle0' });
            
            const pdfOptions = {
                path: outputPath,
                format: 'A4',
                printBackground: true,
                margin: {
                    top: '20mm',
                    right: '20mm',
                    bottom: '20mm',
                    left: '20mm'
                },
                ...options
            };

            await this.page.pdf(pdfOptions);
            return true;
        } catch (error) {
            console.error('PDF generation failed:', error);
            return false;
        }
    }

    async close() {
        if (this.browser) {
            await this.browser.close();
        }
    }
}

module.exports = InvoicePDFGenerator;
