import { Injectable } from '@nestjs/common';
import ExcelJS from 'exceljs';

import type { ExcelExportOptions } from './excel-export.types';

@Injectable()
export class ExcelExportService {
  async buildWorkbookBuffer(options: ExcelExportOptions): Promise<Buffer> {
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet(options.sheetName ?? 'Sheet1');

    worksheet.columns = options.columns.map((column) => ({
      header: column.header,
      key: column.key,
      width: column.width ?? 20,
    }));

    const headerRow = worksheet.getRow(1);
    headerRow.font = { bold: true };

    for (const row of options.rows) {
      worksheet.addRow(row);
    }

    const arrayBuffer = await workbook.xlsx.writeBuffer();
    return Buffer.from(arrayBuffer);
  }
}
