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, unitCost, unit } = body;
    const item = await prisma.supply.update({
      where: { id: parseInt(id) },
      data: { code: code?.toUpperCase().trim(), name: name?.trim(), unitCost: parseSafeFloat(unitCost), unit: unit?.trim() || null }
    });
    return NextResponse.json(item);
  } catch (error: any) {
    if (error.code === 'P2002') return NextResponse.json({ error: 'Código duplicado' }, { status: 409 });
    return NextResponse.json({ error: 'Error updating' }, { status: 500 });
  }
}

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