import { NextResponse } from 'next/server';
import connectDB from '@/lib/mongodb';
import { Product } from '@/models';

/**
 * PUT /api/products/[id]
 * Met à jour un produit
 */
export async function PUT(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    await connectDB();

    const { id } = await context.params;
    const body = await request.json();
    const { 
      productName, 
      category, 
      subCategory,
      description,
      unit,
      purchasePrice,
      salePrice,
      currentStock,
      minStock,
      barcode,
      imageUrl,
      supplierId,
      active 
    } = body;

    const product = await Product.findById(id);
    if (!product) {
      return NextResponse.json(
        {
          success: false,
          error: 'Produit introuvable',
        },
        { status: 404 }
      );
    }

    // Mise à jour
    if (productName) product.productName = productName;
    if (category) product.category = category;
    if (subCategory !== undefined) product.subCategory = subCategory;
    if (description !== undefined) product.description = description;
    if (unit) product.unit = unit;
    if (purchasePrice !== undefined) product.purchasePrice = purchasePrice;
    if (salePrice !== undefined) product.salePrice = salePrice;
    if (currentStock !== undefined) product.currentStock = currentStock;
    if (minStock !== undefined) product.minStock = minStock;
    if (barcode !== undefined) product.barcode = barcode;
    if (imageUrl !== undefined) product.imageUrl = imageUrl;
    if (supplierId !== undefined) product.supplierId = supplierId;
    if (active !== undefined) product.active = active;

    await product.save();

    return NextResponse.json({
      success: true,
      message: 'Produit mis à jour avec succès',
      data: product,
    });
  } catch (error) {
    console.error('Erreur API Products PUT:', error);
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Erreur lors de la mise à jour',
      },
      { status: 500 }
    );
  }
}

/**
 * DELETE /api/products/[id]
 * Supprime (désactive) un produit
 */
export async function DELETE(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    await connectDB();

    const { id } = await context.params;

    const product = await Product.findById(id);
    if (!product) {
      return NextResponse.json(
        {
          success: false,
          error: 'Produit introuvable',
        },
        { status: 404 }
      );
    }

    // Soft delete (désactivation)
    product.active = false;
    await product.save();

    return NextResponse.json({
      success: true,
      message: 'Produit désactivé avec succès',
    });
  } catch (error) {
    console.error('Erreur API Products DELETE:', error);
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Erreur lors de la suppression',
      },
      { status: 500 }
    );
  }
}
