import puppeteer from "puppeteer";
let browser = null;
export async function initBrowser() {
    const execPath = process.env.PUPPETEER_EXECUTABLE_PATH || undefined;
    browser = await puppeteer.launch({
        headless: true,
        executablePath: execPath,
        args: ["--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu", "--disable-dev-shm-usage"],
    });
    console.log("Browser pool ready");
}
export async function closeBrowser() {
    if (browser)
        await browser.close();
}
export async function renderPdf(html, options = {}) {
    if (!browser)
        throw new Error("Browser not initialized");
    const page = await browser.newPage();
    try {
        await page.setContent(html, { waitUntil: "networkidle0", timeout: 15_000 });
        const pdf = await page.pdf({
            format: options.format || "A4",
            landscape: options.landscape || false,
            printBackground: options.printBackground !== false,
            margin: options.margin || {
                top: "20mm",
                right: "15mm",
                bottom: "20mm",
                left: "15mm",
            },
            headerTemplate: options.headerTemplate,
            footerTemplate: options.footerTemplate,
            displayHeaderFooter: options.displayHeaderFooter || false,
        });
        return Buffer.from(pdf);
    }
    finally {
        await page.close();
    }
}
export async function renderUrlPdf(url, options = {}) {
    if (!browser)
        throw new Error("Browser not initialized");
    const page = await browser.newPage();
    try {
        await page.goto(url, {
            waitUntil: options.waitUntil || "networkidle0",
            timeout: 30_000,
        });
        const pdf = await page.pdf({
            format: options.format || "A4",
            landscape: options.landscape || false,
            printBackground: options.printBackground !== false,
            margin: options.margin || {
                top: "20mm",
                right: "15mm",
                bottom: "20mm",
                left: "15mm",
            },
        });
        return Buffer.from(pdf);
    }
    finally {
        await page.close();
    }
}
