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

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

const parseSafeInt = (val: any) => {
  if (val === null || val === undefined || val === '') return undefined;
  const parsed = parseInt(val, 10);
  return isNaN(parsed) ? undefined : parsed;
};

export async function PUT(request: Request, { params }: Params) {
  const { id } = await params;
  try {
    const body = await request.json();
    const { boxTypeCode, flowerType, stemCount } = body;
    const item = await prisma.boxStemCount.update({
      where: { id: parseInt(id) },
      data: {
        boxTypeCode: boxTypeCode?.toUpperCase().trim(),
        flowerType: flowerType?.toUpperCase().trim(),
        stemCount: parseSafeInt(stemCount),
      }
    });
    return NextResponse.json(item);
  } catch (error: any) {
    if (error.code === 'P2002') return NextResponse.json({ error: 'Combinación duplicada' }, { status: 409 });
    return NextResponse.json({ error: 'Error updating' }, { status: 500 });
  }
}

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