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

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: NextRequest, context: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await context.params;
    const body = await request.json();
    const { name, htsCode, nandina, dutyRateEC, dutyRateCO, dutyRateUS, declaredValue, description } = body;
    const item = await prisma.htsProduct.update({
      where: { id },
      data: {
        name: name?.toUpperCase().trim(),
        htsCode: htsCode?.trim(),
        nandina: nandina?.trim(),
        dutyRateEC: parseSafeFloat(dutyRateEC),
        dutyRateCO: parseSafeFloat(dutyRateCO),
        dutyRateUS: parseSafeFloat(dutyRateUS),
        declaredValue: parseSafeFloat(declaredValue),
        description: description || null,
      }
    });
    return NextResponse.json(item);
  } catch (e: any) {
    if (e.code === 'P2002') {
      return NextResponse.json({ error: 'Ya existe este producto.' }, { status: 409 });
    }
    console.error(e);
    return NextResponse.json({ error: 'Error updating HTS entry' }, { status: 500 });
  }
}

export async function DELETE(_: NextRequest, context: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await context.params;
    await prisma.htsProduct.delete({ where: { id } });
    return NextResponse.json({ ok: true });
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: 'Error deleting HTS entry' }, { status: 500 });
  }
}
