import { Injectable } from '@nestjs/common';
import puppeteer from 'puppeteer';
import { MyScheduleMasterService } from './my-schedule-master.service';
import { buildMasterScheduleWorkbook } from '../templates/my-schedule-master.excel.builder';
import { buildMasterSchedulePdfHtml } from '../templates/my-schedule-master.pdf.template';

/**
 * Turns the master-schedule data into downloadable files.
 * Excel via exceljs, PDF via puppeteer (same engine as the NC PDFs).
 */
@Injectable()
export class MyScheduleMasterExportService {
  constructor(private readonly data: MyScheduleMasterService) {}

  async excel(userId: number, q: any): Promise<Buffer> {
    const { records, counts } = await this.data.allRecords(userId, q);
    return buildMasterScheduleWorkbook(records, counts);
  }

  async pdf(userId: number, q: any): Promise<Buffer> {
    const { records, counts } = await this.data.allRecords(userId, q);
    const html = buildMasterSchedulePdfHtml(records, counts);

    const browser = await puppeteer.launch({
      headless: true,
      args: ['--no-sandbox', '--disable-setuid-sandbox'],
    });
    try {
      const page = await browser.newPage();
   await page.setContent(html, { waitUntil: 'domcontentloaded' });
      const pdf = await page.pdf({
        format: 'A4',
        landscape: true,
        printBackground: true,
        margin: { top: '12mm', bottom: '12mm', left: '8mm', right: '8mm' },
      });
      return Buffer.from(pdf);
    } finally {
      await browser.close();
    }
  }
}
