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

export async function POST(request: Request) {
  try {
    const { lineIds, reason } = await request.json();

    if (!Array.isArray(lineIds) || lineIds.length === 0) {
      return NextResponse.json({ error: 'Debes seleccionar al menos una línea/caja para cancelar' }, { status: 400 });
    }

    const cancelReason = (reason || 'Cancelación solicitada por cliente').trim();

    const lines = await prisma.orderLine.findMany({
      where: { id: { in: lineIds } },
      include: {
        order: {
          include: {
            shippingCustomer: true,
            billingCustomer: true,
          }
        },
        product: true,
        farm: true,
      }
    });

    if (lines.length === 0) {
      return NextResponse.json({ error: 'No se encontraron las líneas seleccionadas' }, { status: 404 });
    }

    let archivedLabelsCount = 0;
    let inventoryBoxesCount = 0;

    for (const line of lines) {
      const prevStatus = line.status;

      // 1. Si la orden estaba en status de Finca Asignada (comprada pero no recibida en cuarto frío)
      // Debe cancelarse en pedidos a fincas, archivar la etiqueta a CancelledLabel y notificar a la finca.
      // Esta caja queda en status CANCELADO (NO regresa a NEW)
      if (prevStatus === 'FARM ASIGNED') {
        if (line.boxNumber || line.uniqueCode) {
          const uniqueCode = line.uniqueCode || `${line.farm?.ruc || 'FARM'}-${line.product?.code || 'ITEM'}-${line.boxNumber || '000000'}`;
          try {
            await prisma.cancelledLabel.create({
              data: {
                orderLineId: line.id,
                boxNumber: line.boxNumber || '000000',
                uniqueCode: uniqueCode,
                itemCode: line.product?.code || '—',
                productName: line.product?.name || '—',
                farmId: line.farmId,
                farmName: line.farm?.name,
                customerName: line.order.shippingCustomer?.businessName || line.order.billingCustomer?.businessName,
                po: line.order.po,
                airwayBill: line.airwayBill || line.order.awb,
                agency: line.order.service || 'FEDEX',
                boxType: line.boxType || line.product.boxType,
                farmPrice: line.farmPrice,
                farmDepartureDate: line.farmDepartureDate,
                orderDate: line.order.creationDate,
                reason: `Cancelación directa por parte del cliente: ${cancelReason}`,
              }
            });
            archivedLabelsCount++;
          } catch (e) {
            console.error('Error archiving cancelled label:', e);
          }
        }
      }

      // 2. Si la orden ya estaba Recibida en Cuarto Frío
      // Pasa a estatus CANCELLED pero queda disponible para reasignación de inventario
      if (prevStatus === 'RECEIVED') {
        inventoryBoxesCount++;
      }

      // Actualizar línea a CANCELLED
      await prisma.orderLine.update({
        where: { id: line.id },
        data: {
          status: 'CANCELLED',
          observaciones: `CANCELADA: ${cancelReason}`,
        }
      });

      // Si todas las líneas de esta orden están canceladas, actualizar la orden completa a CANCELLED
      const remainingActiveLines = await prisma.orderLine.count({
        where: {
          orderId: line.orderId,
          status: { not: 'CANCELLED' }
        }
      });

      if (remainingActiveLines === 0) {
        await prisma.order.update({
          where: { id: line.orderId },
          data: { status: 'CANCELLED' }
        });
      }
    }

    let msg = `Se cancelaron exitosamente ${lines.length} caja(s).`;
    if (archivedLabelsCount > 0) {
      msg += ` Se inhabilitaron ${archivedLabelsCount} etiqueta(s) y se registró la cancelación para la finca.`;
    }
    if (inventoryBoxesCount > 0) {
      msg += ` ${inventoryBoxesCount} caja(s) recibidas pasaron a inventario disponible en Cuarto Frío.`;
    }

    return NextResponse.json({
      success: true,
      message: msg,
      cancelledCount: lines.length,
      archivedLabelsCount,
      inventoryBoxesCount
    });

  } catch (error: any) {
    console.error('Error cancelling order lines:', error);
    return NextResponse.json({ error: error.message || 'Error al cancelar las órdenes' }, { status: 500 });
  }
}
