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

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

    const items = await prisma.boxType.findMany({ where, orderBy: { code: 'asc' } });
    return NextResponse.json(items);
  } catch {
    return NextResponse.json({ error: 'Error fetching box types' }, { status: 500 });
  }
}

const parseSafeFloat = (val: unknown) => {
  if (val === null || val === undefined || val === '') return null;
  const parsed = parseFloat(String(val));
  return isNaN(parsed) ? null : parsed;
};

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { code, name, length, width, height, dimWeight, realWeight, farmId, farmName } = body;
    if (!code || !name) return NextResponse.json({ error: 'Código y Nombre son requeridos' }, { status: 400 });
    const item = await prisma.boxType.create({
      data: {
        code: String(code).toUpperCase().trim(),
        name: String(name).trim(),
        length: parseSafeFloat(length),
        width: parseSafeFloat(width),
        height: parseSafeFloat(height),
        dimWeight: parseSafeFloat(dimWeight),
        realWeight: parseSafeFloat(realWeight),
        farmId: farmId || null,
        farmName: farmName || null,
      }
    });
    return NextResponse.json(item);
  } catch (error: unknown) {
    const prismaError = error as { code?: string };
    if (prismaError.code === 'P2002') return NextResponse.json({ error: 'Ya existe un BoxType con ese código' }, { status: 409 });
    console.error("POST BoxType error:", error);
    return NextResponse.json({ error: 'Error creating box type' }, { status: 500 });
  }
}
