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

export async function GET() {
  try {
    const items = await prisma.boxStemCount.findMany({ orderBy: [{ boxTypeCode: 'asc' }, { flowerType: 'asc' }] });
    return NextResponse.json(items);
  } catch {
    return NextResponse.json({ error: 'Error fetching stem counts' }, { status: 500 });
  }
}

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

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { boxTypeCode, flowerType, stemCount } = body;
    if (!boxTypeCode || !flowerType || !stemCount) return NextResponse.json({ error: 'Faltan datos requeridos' }, { status: 400 });
    const item = await prisma.boxStemCount.create({
      data: {
        boxTypeCode: String(boxTypeCode).toUpperCase().trim(),
        flowerType: String(flowerType).toUpperCase().trim(),
        stemCount: parseSafeInt(stemCount),
      }
    });
    return NextResponse.json(item);
  } catch (error: unknown) {
    const prismaError = error as { code?: string };
    if (prismaError.code === 'P2002') return NextResponse.json({ error: 'Ya existe esa combinación BoxType/Flor' }, { status: 409 });
    return NextResponse.json({ error: 'Error creating stem count' }, { status: 500 });
  }
}
