const puppeteer  = require('puppeteer-core');
const buildHtml  = require('./template');

/**
 * Renders the violation document HTML via Puppeteer and returns a PDF buffer.
 * Uses the system Chromium installed in the Alpine image (no separate download).
 * @param {object} violation  - Row from violations JOIN employees
 * @param {object} score      - Row from active_cpas_scores
 * @returns {Buffer}
 */
async function generatePdf(violation, score) {
    const html = buildHtml(violation, score);

    const browser = await puppeteer.launch({
        executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || '/usr/bin/chromium-browser',
        args: [
            '--no-sandbox',
            '--disable-setuid-sandbox',
            '--disable-dev-shm-usage',
            '--disable-gpu',
        ],
        headless: 'new',
    });

    try {
        const page = await browser.newPage();
        await page.setContent(html, { waitUntil: 'networkidle0' });

        const pdf = await page.pdf({
            format:              'Letter',
            printBackground:     true,
            margin: {
                top:    '0.35in',
                bottom: '0.35in',
                left:   '0.4in',
                right:  '0.4in',
            },
            displayHeaderFooter: false,
        });

        return pdf;
    } finally {
        await browser.close();
    }
}

module.exports = generatePdf;
