/**
 * Excel Export Engine — CambioReal branded spreadsheets
 * Uses ExcelJS for .xlsx generation with styled headers
 */
const ExcelJS = require('exceljs');

// CambioReal brand colors
const HEADER_FILL = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF7600BE' } };
const HEADER_FONT = { bold: true, color: { argb: 'FFFFFFFF' }, size: 11 };
const CURRENCY_FORMAT = '#,##0.00';
const PCT_FORMAT = '0.00%';
const DATE_FORMAT = 'yyyy-mm-dd';

/**
 * Generate an Excel workbook from data
 * @param {Object[]} data - Array of row objects
 * @param {Object[]} columns - Column definitions: { header, key, width?, type? }
 *   type: 'currency' | 'percentage' | 'date' | 'number' | 'text' (default)
 * @param {string} sheetName - Worksheet name
 * @returns {ExcelJS.Workbook}
 */
function createWorkbook(data, columns, sheetName = 'Data') {
  const workbook = new ExcelJS.Workbook();
  workbook.creator = 'CambioReal BI-CCC';
  workbook.created = new Date();

  const sheet = workbook.addWorksheet(sheetName);

  // Define columns
  sheet.columns = columns.map(col => ({
    header: col.header,
    key: col.key,
    width: col.width || 15
  }));

  // Style header row
  const headerRow = sheet.getRow(1);
  headerRow.eachCell((cell) => {
    cell.fill = HEADER_FILL;
    cell.font = HEADER_FONT;
    cell.alignment = { vertical: 'middle', horizontal: 'center' };
    cell.border = {
      bottom: { style: 'thin', color: { argb: 'FF5A0091' } }
    };
  });
  headerRow.height = 28;

  // Add data rows
  data.forEach(row => {
    const addedRow = sheet.addRow(row);

    // Apply formatting per column type
    columns.forEach((col, idx) => {
      const cell = addedRow.getCell(idx + 1);
      switch (col.type) {
        case 'currency':
          cell.numFmt = CURRENCY_FORMAT;
          cell.alignment = { horizontal: 'right' };
          break;
        case 'percentage':
          // If value is already 0-100 range, divide by 100 for Excel percentage format
          if (typeof cell.value === 'number' && cell.value > 1) {
            cell.value = cell.value / 100;
          }
          cell.numFmt = PCT_FORMAT;
          cell.alignment = { horizontal: 'right' };
          break;
        case 'date':
          cell.numFmt = DATE_FORMAT;
          break;
        case 'number':
          cell.numFmt = '#,##0';
          cell.alignment = { horizontal: 'right' };
          break;
        default:
          break;
      }
    });
  });

  // Auto-filter
  if (data.length > 0) {
    sheet.autoFilter = {
      from: { row: 1, column: 1 },
      to: { row: data.length + 1, column: columns.length }
    };
  }

  // Freeze header row
  sheet.views = [{ state: 'frozen', ySplit: 1 }];

  return workbook;
}

/**
 * Export workbook to Express response as .xlsx download
 * @param {import('express').Response} res - Express response
 * @param {ExcelJS.Workbook} workbook
 * @param {string} filename - Without extension
 */
async function sendWorkbook(res, workbook, filename) {
  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  res.setHeader('Content-Disposition', `attachment; filename="${filename}.xlsx"`);
  await workbook.xlsx.write(res);
  res.end();
}

/**
 * Quick helper: data + columns → Express download
 */
async function exportToExcel(res, data, columns, sheetName, filename) {
  const workbook = createWorkbook(data, columns, sheetName);
  await sendWorkbook(res, workbook, filename);
}

module.exports = {
  createWorkbook,
  sendWorkbook,
  exportToExcel
};
