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

export async function GET() {
  try {
    const items = await prisma.flowerColor.findMany({ orderBy: { code: 'asc' } });
    return NextResponse.json(items);
  } catch {
    return NextResponse.json({ error: 'Error fetching colors' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { code, name } = body;
    if (!code || !name) return NextResponse.json({ error: 'Código y Nombre son requeridos' }, { status: 400 });
    const item = await prisma.flowerColor.create({
      data: { code: code.toUpperCase().trim(), name: name.trim() }
    });
    return NextResponse.json(item);
  } catch (error: unknown) {
    const prismaError = error as { code?: string };
    if (prismaError.code === 'P2002') return NextResponse.json({ error: 'Ya existe un color con ese código' }, { status: 409 });
    return NextResponse.json({ error: 'Error creating color' }, { status: 500 });
  }
}
