import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/api-guards';
import * as XLSX from 'xlsx';

// GET: Export consolidated commission report as Excel (restricted to admin, director, analyst)
export const GET = withAuth(async (req, { prisma }) => {
  try {
    const { searchParams } = req.nextUrl;
    const period = searchParams.get('period');

    const whereClause: any = {};
    if (period) whereClause.period = period;

    // Fetch settlements with collaborator, hotel, region and plan details
    const settlements = await prisma.settlement.findMany({
      where: whereClause,
      include: {
        colaborador: {
          include: {
            hotel: {
              include: {
                region: true
              }
            }
          }
        },
        plan: true
      },
      orderBy: { period: 'desc' }
    });

    if (settlements.length === 0) {
      return NextResponse.json({ error: 'No se encontraron liquidaciones para exportar.' }, { status: 404 });
    }

    // 1. Build Detailed Sheet Data
    const detailedData = settlements.map((s: any) => ({
      'Periodo': s.period,
      'Colaborador': s.colaborador.username,
      'Correo': s.colaborador.email,
      'Hotel': s.colaborador.hotel.name,
      'Region': s.colaborador.hotel.region.name,
      'Plan': s.plan.name,
      'Meta de Ventas': parseFloat(s.goalAmount.toString()),
      'Ventas Realizadas': parseFloat(s.salesAmount.toString()),
      '% Cumplimiento': parseFloat(s.achievementPercentage.toString()) * 100,
      'Comisión Calculada': parseFloat(s.calculatedCommission.toString()),
      'Ajuste/Clawback': parseFloat(s.adjustmentAmount.toString()),
      'Pago Total': parseFloat(s.totalPayout.toString()),
      'Estado': s.status
    }));

    // 2. Build Summary Sheet Data (Grouped by Region and Hotel)
    const hotelSummaryMap: Record<string, {
      'Region': string;
      'Hotel': string;
      'Colaboradores': number;
      'Ventas Totales': number;
      'Comisiones Pagadas': number;
      'Clawbacks Netos': number;
      'Total Pagado': number;
    }> = {};

    for (const s of settlements) {
      const hotelCode = s.colaborador.hotel.code;
      const hotelName = s.colaborador.hotel.name;
      const regionName = s.colaborador.hotel.region.name;
      
      const payout = parseFloat(s.totalPayout.toString());
      const sales = parseFloat(s.salesAmount.toString());
      const commission = parseFloat(s.calculatedCommission.toString());
      const adjustment = parseFloat(s.adjustmentAmount.toString());

      if (!hotelSummaryMap[hotelCode]) {
        hotelSummaryMap[hotelCode] = {
          'Region': regionName,
          'Hotel': hotelName,
          'Colaboradores': 0,
          'Ventas Totales': 0,
          'Comisiones Pagadas': 0,
          'Clawbacks Netos': 0,
          'Total Pagado': 0
        };
      }

      hotelSummaryMap[hotelCode]['Colaboradores']++;
      hotelSummaryMap[hotelCode]['Ventas Totales'] += sales;
      if (s.status === 'APPROVED') {
        hotelSummaryMap[hotelCode]['Comisiones Pagadas'] += commission;
        hotelSummaryMap[hotelCode]['Clawbacks Netos'] += adjustment;
        hotelSummaryMap[hotelCode]['Total Pagado'] += payout;
      }
    }

    const summaryData = Object.values(hotelSummaryMap);

    // 3. Assemble Excel Workbook
    const wb = XLSX.utils.book_new();
    
    const wsSummary = XLSX.utils.json_to_sheet(summaryData);
    const wsDetailed = XLSX.utils.json_to_sheet(detailedData);

    // Append sheets
    XLSX.utils.book_append_sheet(wb, wsSummary, 'Resumen por Hotel');
    XLSX.utils.book_append_sheet(wb, wsDetailed, 'Detalle Liquidaciones');

    // Write workbook to buffer
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'buffer' });

    const filename = period 
      ? `Reporte_Consolidado_${period}.xlsx` 
      : 'Reporte_Consolidado_Comisiones.xlsx';

    return new Response(excelBuffer, {
      headers: {
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'Content-Disposition': `attachment; filename="${filename}"`
      }
    });

  } catch (err: any) {
    console.error('Failed to export Excel report:', err);
    return NextResponse.json({ error: 'Failed to export Excel report' }, { status: 500 });
  }
}, ['admin', 'director', 'analyst']);
