const fs = require('fs');
const path = require('path');
const XLSX = require('xlsx');

const templatesDir = path.join(__dirname, '..', 'public', 'templates');
if (!fs.existsSync(templatesDir)) {
  fs.mkdirSync(templatesDir, { recursive: true });
}

// 1. Template Sheet (Clean layout)
const templateData = [
  {
    "Colaborador": "colaborador_mde",
    "Periodo": "2026-06",
    "Hotel": "EST-MDE",
    "Monto": 15000.00,
    "Cantidad": 5,
    "Id_Transaccion": "TX-EST-MDE-001"
  }
];

const templateWorkbook = XLSX.utils.book_new();
const templateWorksheet = XLSX.utils.json_to_sheet(templateData);
XLSX.utils.book_append_sheet(templateWorkbook, templateWorksheet, "Template");
XLSX.writeFile(templateWorkbook, path.join(templatesDir, 'import_sales_template.xlsx'));
console.log("Created import_sales_template.xlsx successfully!");

// 2. Test Sheet (Contains both valid and invalid records to test API validation output)
const testData = [
  // Valid row
  {
    "Colaborador": "colaborador_mde",
    "Periodo": "2026-06",
    "Hotel": "EST-MDE",
    "Monto": 25000.00,
    "Cantidad": 10,
    "Id_Transaccion": "TX-E2E-001"
  },
  // Valid row
  {
    "Colaborador": "colaborador_mde",
    "Periodo": "2026-06",
    "Hotel": "EST-MDE",
    "Monto": 5000.00,
    "Cantidad": 2,
    "Id_Transaccion": "TX-E2E-002"
  },
  // Invalid row: Non-existent Colaborador
  {
    "Colaborador": "colaborador_inexistente",
    "Periodo": "2026-06",
    "Hotel": "EST-MDE",
    "Monto": 10000.00,
    "Cantidad": 3,
    "Id_Transaccion": "TX-E2E-003"
  },
  // Invalid row: Invalid Period format
  {
    "Colaborador": "colaborador_mde",
    "Periodo": "2026/06",
    "Hotel": "EST-MDE",
    "Monto": 12000.00,
    "Cantidad": 4,
    "Id_Transaccion": "TX-E2E-004"
  },
  // Invalid row: Non-existent Hotel
  {
    "Colaborador": "colaborador_mde",
    "Periodo": "2026-06",
    "Hotel": "EST-FAKE",
    "Monto": 8000.00,
    "Cantidad": 1,
    "Id_Transaccion": "TX-E2E-005"
  },
  // Invalid row: Negative amount
  {
    "Colaborador": "colaborador_mde",
    "Periodo": "2026-06",
    "Hotel": "EST-MDE",
    "Monto": -500.00,
    "Cantidad": 2,
    "Id_Transaccion": "TX-E2E-006"
  }
];

const testWorkbook = XLSX.utils.book_new();
const testWorksheet = XLSX.utils.json_to_sheet(testData);
XLSX.utils.book_append_sheet(testWorkbook, testWorksheet, "TestData");
XLSX.writeFile(testWorkbook, path.join(templatesDir, 'import_sales_test.xlsx'));
console.log("Created import_sales_test.xlsx successfully!");
