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

export async function GET() {
  try {
    const templateData = [
      {
        'NOMBRE DEL PRODUCTO': 'ROSES',
        'HTS CODE (USA)': '0603.11.00.10',
        'NANDINA (ECUADOR)': '0603110010',
        'DUTY EC (%)': 6.8,
        'DUTY CO (%)': 12.5,
        'DUTY US (%)': 0.0,
        'COSTO DECLARADO POR TALLO ($)': 0.25,
        'DESCRIPCION ADUANA': 'Fresh cut roses'
      },
      {
        'NOMBRE DEL PRODUCTO': 'CARNATION',
        'HTS CODE (USA)': '0603.12.70.00',
        'NANDINA (ECUADOR)': '0603129000',
        'DUTY EC (%)': 6.4,
        'DUTY CO (%)': 12.5,
        'DUTY US (%)': 0.0,
        'COSTO DECLARADO POR TALLO ($)': 0.12,
        'DESCRIPCION ADUANA': 'Fresh cut carnations'
      },
      {
        'NOMBRE DEL PRODUCTO': 'LISIANTHUS',
        'HTS CODE (USA)': '0603.19.01.60',
        'NANDINA (ECUADOR)': '0603199090',
        'DUTY EC (%)': 4.0,
        'DUTY CO (%)': 12.5,
        'DUTY US (%)': 0.0,
        'COSTO DECLARADO POR TALLO ($)': 0.20,
        'DESCRIPCION ADUANA': 'Fresh cut lisianthus'
      }
    ];

    const ws = XLSX.utils.json_to_sheet(templateData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Plantilla HTS');
    const buffer = XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });

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