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

export async function PUT(request: NextRequest, context: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await context.params;
    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 !== undefined && stems !== '' ? parseInt(stems) : null);

    // Delete existing recipes and re-create (simple replace strategy)
    await prisma.recipe.deleteMany({ where: { productId: id } });

    const product = await prisma.product.update({
      where: { id },
      data: {
        code, name, tariffCode,
        htsCode: finalHtsCode,
        nandina,
        dutyRate: dutyRate !== undefined && dutyRate !== '' ? parseFloat(dutyRate) : null,
        declaredValue: declaredValue !== undefined && declaredValue !== '' ? parseFloat(declaredValue) : null,
        country, originCity, service, productType, packType, boxType,
        length: length !== undefined && length !== '' ? parseFloat(length) : null,
        width: width !== undefined && width !== '' ? parseFloat(width) : null,
        height: height !== undefined && height !== '' ? parseFloat(height) : null,
        dimWeight: dimWeight !== undefined && dimWeight !== '' ? parseFloat(dimWeight) : null,
        realWeight: realWeight !== undefined && 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 (e) {
    console.error(e);
    return NextResponse.json({ error: 'Error updating product' }, { status: 500 });
  }
}

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