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

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const status = searchParams.get('status');
    const farmId = searchParams.get('farmId');
    const where: any = {};
    if (status) where.status = status;
    if (farmId) {
      where.lines = {
        some: {
          farmId
        }
      };
    }

    const orders = await prisma.order.findMany({
      where,
      include: {
        billingCustomer:  true,
        shippingCustomer: true,
        masterCustomer:   true,
        lines: {
          include: {
            product: {
              include: { recipes: true }
            },
            farm:    true,
          }
        }
      },
      orderBy: { createdAt: 'desc' },
    });
    return NextResponse.json(orders);
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: 'Error fetching orders' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { po, orderNumber, billingCustomerId, shippingCustomerId, deliveryDate, isReplacement, lines } = body;

    const order = await prisma.order.create({
      data: {
        po,
        orderNumber,
        creationDate: new Date(),
        deliveryDate: new Date(deliveryDate),
        isReplacement: isReplacement || false,
        billingCustomer:  billingCustomerId  ? { connect: { id: billingCustomerId } }  : undefined,
        shippingCustomer: shippingCustomerId ? { connect: { id: shippingCustomerId } } : undefined,
        lines: lines?.length ? {
          create: lines.map((l: { productId: string; farmId?: string; quantity: number; unitPrice?: number; price?: number }) => ({
            product:   { connect: { id: l.productId } },
            farm:      l.farmId ? { connect: { id: l.farmId } } : undefined,
            quantity:  Number(l.quantity),
            price:     Number(l.price || l.unitPrice || 0),
          }))
        } : undefined,
      },
      include: {
        billingCustomer:  { select: { businessName: true } },
        shippingCustomer: { select: { businessName: true } },
        lines: { include: { product: true, farm: true } },
      }
    });

    return NextResponse.json(order);
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: 'Error creating order' }, { status: 500 });
  }
}
