import { Presenter } from "@erp/core/api";
import puppeteer from "puppeteer";
import report from "puppeteer-report";
import { CustomerInvoice } from "../../../../domain";
import { CustomerInvoiceReportHTMLPresenter } from "./customer-invoice.report.html";

// https://plnkr.co/edit/lWk6Yd?preview

export class CustomerInvoiceReportPDFPresenter extends Presenter<
  CustomerInvoice,
  Promise<Buffer<ArrayBuffer>>
> {
  async toOutput(customerInvoice: CustomerInvoice): Promise<Buffer<ArrayBuffer>> {
    try {
      const htmlPresenter = this.presenterRegistry.getPresenter({
        resource: "customer-invoice",
        projection: "REPORT",
        format: "HTML",
      }) as CustomerInvoiceReportHTMLPresenter;

      const htmlData = htmlPresenter.toOutput(customerInvoice);

      // Generar el PDF con Puppeteer
      const browser = await puppeteer.launch({
        args: [
          "--disable-extensions",
          "--no-sandbox",
          "--disable-setuid-sandbox",
          "--disable-dev-shm-usage",
          "--disable-gpu",
        ],
      });

      const page = await browser.newPage();
      const navigationPromise = page.waitForNavigation();
      await page.setContent(htmlData, { waitUntil: "networkidle2" });

      await navigationPromise;

      const reportPDF = await report.pdfPage(page, {
        format: "A4",
        margin: {
          bottom: "10mm",
          left: "10mm",
          right: "10mm",
          top: "10mm",
        },
        landscape: false,
        preferCSSPageSize: true,
        omitBackground: false,
        printBackground: true,
        displayHeaderFooter: false,
        headerTemplate: "<div />",
        footerTemplate:
          '<div style="text-align: center;width: 297mm;font-size: 10px;">Página <span style="margin-right: 1cm"><span class="pageNumber"></span> de <span class="totalPages"></span></span></div>',
      });

      await browser.close();
      return Buffer.from(reportPDF);
    } catch (err: unknown) {
      console.error(err);
      throw err as Error;
    }
  }
}
