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

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

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

export async function PUT(request: Request, { params }: Params) {
  const { id } = await params;
  try {
    const body = await request.json();
    const { code, name, length, width, height, dimWeight, realWeight } = body;
    const item = await prisma.boxType.update({
      where: { id: parseInt(id) },
      data: {
        code: code?.toUpperCase().trim(),
        name: name?.trim(),
        length: parseSafeFloat(length),
        width: parseSafeFloat(width),
        height: parseSafeFloat(height),
        dimWeight: parseSafeFloat(dimWeight),
        realWeight: parseSafeFloat(realWeight),
      }
    });
    return NextResponse.json(item);
  } catch (error: any) {
    if (error.code === 'P2002') return NextResponse.json({ error: 'Código duplicado' }, { status: 409 });
    console.error("PUT BoxType error:", error);
    return NextResponse.json({ error: 'Error updating' }, { status: 500 });
  }
}

export async function DELETE(_: Request, { params }: Params) {
  const { id } = await params;
  try {
    await prisma.boxType.delete({ where: { id: parseInt(id) } });
    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ error: 'Error deleting' }, { status: 500 });
  }
}
