import { NextResponse } from 'next/server';
import * as XLSX from 'xlsx';

export async function GET() {
  try {
    const wb = XLSX.utils.book_new();

    // Headers exactos del formato UPS (Sheet1) - 49 columnas
    const headers = [
      "Tracking","Company","eBinv","Orddate","Shipto","Shipto2","Address","Address2",
      "City","State","Zip","Phone","Soldto","Soldto2","STPhone","Ponumber","CUSTnbr",
      "SHIPDT","Deliver","SatDel","Quantity","Item","ProdDesc","Length","Width",
      "Height","WeightKg","DclValue","Message","Service","PkgType","GenDesc",
      "ShipCtry","Currency","Origin","UOM","TPComp","TPAttn","TPAdd1","TPCity",
      "TPState","TPCtry","TPZip","TPPhone","TPAcct","Farm","MSG","AWB","OBSERVACIONES"
    ];

    // Fila de ejemplo 1
    const exampleRow1 = [
      "1Z73X65X6642188826", "Global Floral Inc", "", "44686", "Marina Kishko", "", "123 Main St", "",
      "Miami", "FL", "33101", "305-555-1234", "Global Floral Inc", "", "305-555-1234", "3254", "3254",
      "", "44692", "", 1, "100873", "Ranunculus White 40 - 45cm PK80", "", "",
      "", "", "", "", "", "", "",
      "", "", "", "", "", "", "", "",
      "", "", "", "", "", "SANDE", "N", "406-0853 2322", "OBSEQUIO CLIENTE"
    ];

    // Fila de ejemplo 2
    const exampleRow2 = [
      "1Z73X65X6641972239", "Global Floral Inc", "", "44686", "Joanne Beck", "", "456 Oak Ave", "",
      "Orlando", "FL", "32801", "407-555-9876", "Global Floral Inc", "", "407-555-9876", "3175", "3175",
      "", "44692", "", 1, "100717", "Roses Ht pink & Biclr Pink 50cm PK50", "", "",
      "", "", "", "", "", "", "",
      "", "", "", "", "", "", "", "",
      "", "", "", "", "", "ROSELY", "N", "406-0853 2322", "FULL MONTY + PALOMA"
    ];

    const wsData = [headers, exampleRow1, exampleRow2];
    const ws = XLSX.utils.aoa_to_sheet(wsData);

    // Ajustar algunos anchos de columna para mejor legibilidad
    ws['!cols'] = headers.map((h) => {
      const widths: Record<string, number> = {
        'Tracking': 20, 'Company': 20, 'Orddate': 12, 'Shipto': 20, 'Address': 25,
        'City': 15, 'Phone': 15, 'Soldto': 20, 'STPhone': 15, 'Ponumber': 12,
        'CUSTnbr': 12, 'Deliver': 12, 'ProdDesc': 35, 'Farm': 15, 'AWB': 18,
        'OBSERVACIONES': 25
      };
      return { wch: widths[h] || 10 };
    });

    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    const buffer = XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });

    return new Response(buffer, {
      headers: {
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'Content-Disposition': 'attachment; filename="FORMATO_UPS_USFLORAL.xlsx"',
      },
    });
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: 'Error generating template' }, { status: 500 });
  }
}
