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

export async function GET() {
  try {
    const products = await prisma.product.findMany({
      orderBy: { name: 'asc' },
      include: { recipes: true },
    });
    return NextResponse.json(products);
  } catch {
    return NextResponse.json({ error: 'Error fetching products' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { code, name, tariffCode, htsCode, nandina, dutyRate, declaredValue, country, originCity, service, productType, packType, boxType, length, width, height, dimWeight, realWeight, stems, recipeFormat, recipes } = body;
    
    // First recipe's HTS code takes priority if recipes exist
    const firstRecipeHts = recipes?.find((r: { hts?: string }) => r.hts?.trim())?.hts?.trim();
    const finalHtsCode = firstRecipeHts || htsCode || null;
    
    // Calculate total stems from recipes if available
    const calculatedStems = recipes?.reduce((sum: number, r: { quantity?: string; pack?: string }) => {
      const q = parseFloat(r.quantity || '0') || 0;
      const p = parseFloat(r.pack || '0') || 0;
      return sum + (q * p);
    }, 0);
    const finalStems = calculatedStems && calculatedStems > 0 ? Math.round(calculatedStems) : (stems ? parseInt(stems) : null);

    const product = await prisma.product.create({
      data: {
        code, name, tariffCode,
        htsCode: finalHtsCode,
        nandina,
        dutyRate: dutyRate ? parseFloat(dutyRate) : null,
        declaredValue: declaredValue ? parseFloat(declaredValue) : null,
        country, originCity, service, productType, packType, boxType,
        length: length ? parseFloat(length) : null,
        width: width ? parseFloat(width) : null,
        height: height ? parseFloat(height) : null,
        dimWeight: dimWeight ? parseFloat(dimWeight) : null,
        realWeight: realWeight ? parseFloat(realWeight) : null,
        stems: finalStems,
        recipeFormat: recipeFormat || 'Bouquet',
        recipes: recipes && recipes.length > 0 ? {
          create: recipes.map((r: { quantity?: string; pack?: string; productList?: string; length?: string; hts?: string; nandina?: string; color?: string; stemValueDeclared?: string; totalValue?: string; dclValue?: string }) => ({
            quantity: r.quantity || null,
            pack: r.pack || null,
            productList: r.productList || null,
            length: r.length || null,
            hts: r.hts || null,
            nandina: r.nandina || null,
            color: r.color || null,
            stemValueDeclared: r.stemValueDeclared || null,
            totalValue: r.totalValue || null,
            dclValue: r.dclValue || null,
          }))
        } : undefined,
      },
      include: { recipes: true },
    });
    return NextResponse.json(product);
  } catch (error: unknown) {
    if ((error as { code?: string }).code === 'P2002') return NextResponse.json({ error: 'Ya existe un producto con ese código (Item)' }, { status: 409 });
    return NextResponse.json({ error: 'Error creating product' }, { status: 500 });
  }
}
