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

export async function GET(request: NextRequest, context: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await context.params;
    const line = await prisma.orderLine.findUnique({
      where: { id },
      include: {
        order: {
          include: {
            shippingCustomer: true,
            billingCustomer: true,
            masterCustomer: true
          }
        },
        product: true,
        farm: true
      }
    });
    if (!line) return NextResponse.json({ error: 'Línea de orden no encontrada' }, { status: 404 });
    return NextResponse.json(line);
  } catch (error: any) {
    return NextResponse.json({ error: error.message || 'Error fetching order line' }, { status: 500 });
  }
}

export async function PUT(request: NextRequest, context: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await context.params;
    const data = await request.json();
    
    // Validamos que la línea exista
    const line = await prisma.orderLine.findUnique({
      where: { id },
      include: { order: true }
    });
    
    if (!line) {
      return NextResponse.json({ error: 'Línea de orden no encontrada' }, { status: 404 });
    }

    let productUpdateId = line.productId;
    if (data.productCode) {
       // Buscar el producto por código
       const p = await prisma.product.findUnique({ where: { code: data.productCode } });
       if (p) {
         productUpdateId = p.id;
       } else {
         return NextResponse.json({ error: `El producto ${data.productCode} no existe.` }, { status: 400 });
       }
    }

    // Actualizamos la línea
    const updatedLine = await prisma.orderLine.update({
      where: { id },
      data: {
        productId: productUpdateId,
        quantity: data.quantity ? parseInt(data.quantity.toString()) : undefined,
      }
    });

    if (data.date) {
       await prisma.order.update({
         where: { id: line.orderId },
         data: {
           creationDate: new Date(data.date),
         }
       })
    }

    return NextResponse.json(updatedLine);
  } catch (error: any) {
    console.error("Error updating order line:", error);
    return NextResponse.json({ error: error.message || 'Error al actualizar la línea' }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest, context: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await context.params;
    const line = await prisma.orderLine.findUnique({ where: { id } });
    if (!line) return NextResponse.json({ error: 'Not found' }, { status: 404 });

    await prisma.orderLine.delete({
      where: { id }
    });

    // Si la orden queda vacía, la eliminamos
    const remaining = await prisma.orderLine.count({
      where: { orderId: line.orderId }
    });
    
    if (remaining === 0) {
      await prisma.order.delete({ where: { id: line.orderId }});
    }

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error("Error deleting order line:", error);
    return NextResponse.json({ error: 'Error al eliminar' }, { status: 500 });
  }
}
