import type { NextApiRequest, NextApiResponse } from "next";
import puppeteer from "puppeteer-core";
import { env } from "~/env";

export default async function handler(
	req: NextApiRequest,
	res: NextApiResponse,
) {
	let browser = null;

	try {
		browser = await puppeteer.connect({
			browserWSEndpoint: env.BROWSER_WS_URL,
		});

		const page = await browser.newPage();

		if (req.cookies && Object.keys(req.cookies).length > 0) {
			const productionDomain = new URL(env.INTERNAL_BASE_URL).hostname;

			const cookies = Object.entries(req.cookies).map(([name, value]) => ({
				name,
				value: value || "",
				domain:
					env.NODE_ENV === "production"
						? productionDomain
						: "host.docker.internal",
				path: "/",
			}));
			await browser.setCookie(...cookies);
		}

		const baseUrl =
			env.NODE_ENV === "production"
				? env.INTERNAL_BASE_URL
				: `http://host.docker.internal:3000`;
		const targetUrl = `${baseUrl}/area-riservata/admin/scheda-annuncio-stampa/${req.query.id}?raw=true`;
		await page.goto(targetUrl, { waitUntil: "networkidle0" });

		const pdf = await page.pdf({
			format: "A4",
			printBackground: true,
		});

		res.setHeader("Content-Type", "application/pdf");
		res.send(Buffer.from(pdf));
	} catch (error) {
		console.error("PDF Generation Error:", error);
		res.status(500).json({ error: "Failed to generate PDF" });
	} finally {
		// 'disconnect' tells browserless you're done with this tab
		if (browser) await browser.disconnect();
	}
}
