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

export async function GET() {
  try {
    const daes = await prisma.dae.findMany({
      include: { farm: { select: { id: true, name: true } } },
      orderBy: { createdAt: 'desc' },
    });
    return NextResponse.json(daes);
  } catch {
    return NextResponse.json({ error: 'Error fetching DAEs' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { daeNumber, farmId, exportDate, status, totalBoxes, totalWeight, airlineCode, flightNumber, destination, notes } = body;
    if (!daeNumber) return NextResponse.json({ error: 'Número de DAE requerido' }, { status: 400 });
    const dae = await prisma.dae.create({
      data: {
        daeNumber,
        farmId: farmId || null,
        exportDate: exportDate ? new Date(exportDate) : null,
        status: status || 'ACTIVE',
        totalBoxes: totalBoxes ? parseInt(totalBoxes) : null,
        totalWeight: totalWeight ? parseFloat(totalWeight) : null,
        airlineCode: airlineCode || null,
        flightNumber: flightNumber || null,
        destination: destination || null,
        notes: notes || null,
      },
      include: { farm: true },
    });
    return NextResponse.json(dae, { status: 201 });
  } catch (e: any) {
    if (e?.code === 'P2002') return NextResponse.json({ error: 'Número de DAE ya existe' }, { status: 409 });
    return NextResponse.json({ error: 'Error al crear DAE' }, { status: 500 });
  }
}
