import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const awb = searchParams.get('awb')?.trim();

    if (!awb) {
      return NextResponse.json({ error: 'Parámetro AWB requerido' }, { status: 400 });
    }

    // Find all matching order lines
    const lines = await prisma.orderLine.findMany({
      where: {
        OR: [
          { airwayBill: { contains: awb } },
          { order: { awb: { contains: awb } } }
        ]
      },
      include: {
        order: {
          include: {
            shippingCustomer: true,
            billingCustomer: true,
            masterCustomer: true
          }
        },
        product: true,
        farm: true
      },
      orderBy: { createdAt: 'asc' }
    });

    // Also look up Guia AirwayBill details
    const matchedGuia = await prisma.airwayBill.findFirst({
      where: { awb: { contains: awb } }
    });

    const agency = matchedGuia?.agency || lines[0]?.order?.service || 'FEDEX';

    // Helper to map box type string to standard column (ST, EB, QB, HB)
    const normalizeBoxCategory = (boxTypeStr?: string | null): 'ST' | 'EB' | 'QB' | 'HB' => {
      const b = (boxTypeStr || '').toUpperCase();
      if (b.startsWith('EB')) return 'EB';
      if (b.startsWith('QB')) return 'QB';
      if (b.startsWith('HB')) return 'HB';
      if (b.startsWith('ST')) return 'ST';
      return 'EB'; // default
    };

    // Item aggregation map
    type ItemRow = {
      item: string;
      productName: string;
      pack: number;
      stemsPerBunch: number;
      stemsPerBox: number;
      weightKg: number;
      dimWeightKg: number;
      st: number;
      eb: number;
      qb: number;
      hb: number;
      totalBoxes: number;
      totalStems: number;
      totalKg: number;
      farmName: string;
    };

    const itemMap = new Map<string, ItemRow>();
    const farmMap = new Map<string, Map<string, ItemRow>>();

    let grandST = 0;
    let grandEB = 0;
    let grandQB = 0;
    let grandHB = 0;
    let grandTotalPieces = 0;
    let grandTotalStems = 0;
    let grandTotalRealWeight = 0;
    let grandTotalDimWeight = 0;

    lines.forEach(line => {
      const prod = line.product;
      const farmName = line.farm?.name || 'SIN FINCA';
      const itemCode = prod.code || 'GENERIC';
      const prodName = prod.name || 'Flor';

      const stemsPerBox = prod.stems || 200;
      const pack = prod.packType ? parseInt(prod.packType, 10) || 8 : 8;
      const stemsPerBunch = Math.round(stemsPerBox / Math.max(1, pack));

      const boxCategory = normalizeBoxCategory(line.product.boxType);
      const qty = line.quantity || 1;

      // Real weight and Dim weight
      const l = prod.length || 104;
      const w = prod.width || 18;
      const h = prod.height || 14;
      const dimKg = prod.dimWeight || Math.round(((l * w * h) / 6000) * 100) / 100;
      const realKg = prod.realWeight || 14.4;

      const lineTotalKg = Math.round((realKg * qty) * 100) / 100;
      const lineTotalStems = stemsPerBox * qty;

      // Accumulate Grand Totals
      if (boxCategory === 'ST') grandST += qty;
      if (boxCategory === 'EB') grandEB += qty;
      if (boxCategory === 'QB') grandQB += qty;
      if (boxCategory === 'HB') grandHB += qty;
      grandTotalPieces += qty;
      grandTotalStems += lineTotalStems;
      grandTotalRealWeight += lineTotalKg;
      grandTotalDimWeight += dimKg * qty;

      // 1. Group by Item
      if (!itemMap.has(itemCode)) {
        itemMap.set(itemCode, {
          item: itemCode,
          productName: prodName,
          pack,
          stemsPerBunch,
          stemsPerBox,
          weightKg: realKg,
          dimWeightKg: dimKg,
          st: 0,
          eb: 0,
          qb: 0,
          hb: 0,
          totalBoxes: 0,
          totalStems: 0,
          totalKg: 0,
          farmName
        });
      }
      const itemRow = itemMap.get(itemCode)!;
      if (boxCategory === 'ST') itemRow.st += qty;
      if (boxCategory === 'EB') itemRow.eb += qty;
      if (boxCategory === 'QB') itemRow.qb += qty;
      if (boxCategory === 'HB') itemRow.hb += qty;
      itemRow.totalBoxes += qty;
      itemRow.totalStems += lineTotalStems;
      itemRow.totalKg += lineTotalKg;

      // 2. Group by Farm
      if (!farmMap.has(farmName)) {
        farmMap.set(farmName, new Map<string, ItemRow>());
      }
      const farmItems = farmMap.get(farmName)!;
      if (!farmItems.has(itemCode)) {
        farmItems.set(itemCode, {
          item: itemCode,
          productName: prodName,
          pack,
          stemsPerBunch,
          stemsPerBox,
          weightKg: realKg,
          dimWeightKg: dimKg,
          st: 0,
          eb: 0,
          qb: 0,
          hb: 0,
          totalBoxes: 0,
          totalStems: 0,
          totalKg: 0,
          farmName
        });
      }
      const farmItemRow = farmItems.get(itemCode)!;
      if (boxCategory === 'ST') farmItemRow.st += qty;
      if (boxCategory === 'EB') farmItemRow.eb += qty;
      if (boxCategory === 'QB') farmItemRow.qb += qty;
      if (boxCategory === 'HB') farmItemRow.hb += qty;
      farmItemRow.totalBoxes += qty;
      farmItemRow.totalStems += lineTotalStems;
      farmItemRow.totalKg += lineTotalKg;
    });

    const itemsSummary = Array.from(itemMap.values());

    const farmsSummary = Array.from(farmMap.entries()).map(([fName, itemsInFarm]) => {
      const rows = Array.from(itemsInFarm.values());
      const farmST = rows.reduce((s, r) => s + r.st, 0);
      const farmEB = rows.reduce((s, r) => s + r.eb, 0);
      const farmQB = rows.reduce((s, r) => s + r.qb, 0);
      const farmHB = rows.reduce((s, r) => s + r.hb, 0);
      const farmTotalBoxes = farmST + farmEB + farmQB + farmHB;
      const farmTotalStems = rows.reduce((s, r) => s + r.totalStems, 0);
      const farmTotalKg = rows.reduce((s, r) => s + r.totalKg, 0);

      return {
        farmName: fName,
        rows,
        subtotals: {
          st: farmST,
          eb: farmEB,
          qb: farmQB,
          hb: farmHB,
          totalBoxes: farmTotalBoxes,
          totalStems: farmTotalStems,
          totalKg: Math.round(farmTotalKg * 100) / 100
        }
      };
    });

    return NextResponse.json({
      awb,
      agency,
      deliverDate: matchedGuia?.deliverDate || lines[0]?.order?.deliveryDate || null,
      shipDate: matchedGuia?.shipDate || lines[0]?.order?.shipdt || null,
      totalLines: lines.length,
      grandTotals: {
        st: grandST,
        eb: grandEB,
        qb: grandQB,
        hb: grandHB,
        totalPieces: grandTotalPieces,
        totalStems: grandTotalStems,
        totalRealWeight: Math.round(grandTotalRealWeight * 100) / 100,
        totalDimWeight: Math.round(grandTotalDimWeight * 100) / 100
      },
      itemsSummary,
      farmsSummary
    });

  } catch (error: any) {
    console.error('Error generating AWB Master Report data:', error);
    return NextResponse.json({ error: error.message || 'Error al generar reporte de AWB' }, { status: 500 });
  }
}
