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

type Params = { params: Promise<{ id: string }> };

export async function GET(request: Request, { params }: Params) {
  const { id } = await params;
  try {
    const po = await prisma.purchaseOrder.findUnique({
      where: { id },
      include: { farm: true, lines: true },
    });
    if (!po) return NextResponse.json({ error: 'Not found' }, { status: 404 });
    return NextResponse.json(po);
  } catch {
    return NextResponse.json({ error: 'Error' }, { status: 500 });
  }
}

export async function PUT(request: Request, { params }: Params) {
  const { id } = await params;
  try {
    const body = await request.json();
    const { poNumber, farmId, deliveryDate, status, notes } = body;
    const po = await prisma.purchaseOrder.update({
      where: { id },
      data: {
        poNumber,
        farmId: farmId || null,
        deliveryDate: deliveryDate ? new Date(deliveryDate) : null,
        status,
        notes: notes || null,
      },
      include: { farm: true, lines: true },
    });
    return NextResponse.json(po);
  } catch (e: any) {
    if (e?.code === 'P2002') return NextResponse.json({ error: 'Número de pedido ya existe' }, { status: 409 });
    return NextResponse.json({ error: 'Error al actualizar' }, { status: 500 });
  }
}

export async function DELETE(request: Request, { params }: Params) {
  const { id } = await params;
  try {
    await prisma.purchaseOrder.delete({ where: { id } });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: 'Error al eliminar' }, { status: 500 });
  }
}
