/* eslint-disable @typescript-eslint/no-explicit-any */
import { NextResponse } from 'next/server';
import connectDB from '@/lib/mongodb';
import { Product } from '@/models';

/**
 * GET /api/products
 * Retourne tous les produits
 */
export async function GET(request: Request) {
  try {
    await connectDB();

    const { searchParams } = new URL(request.url);
    const category = searchParams.get('category');

    const filter: any = {};
    if (category && category !== 'ALL') {
      filter.category = category;
    }

    const products = await Product.find(filter)
      .populate('supplierId', 'supplierName')
      .sort({ productName: 1 })
      .lean();

    return NextResponse.json({
      success: true,
      data: products,
    });
  } catch (error) {
    console.error('Erreur API Products GET:', error);
    return NextResponse.json(
      {
        success: false,
        error: 'Erreur lors de la récupération des produits',
      },
      { status: 500 }
    );
  }
}

/**
 * POST /api/products
 * Crée un nouveau produit
 */
export async function POST(request: Request) {
  try {
    await connectDB();

    const body = await request.json();
    const { 
      productCode, 
      productName, 
      category, 
      subCategory,
      description,
      unit,
      purchasePrice,
      salePrice,
      currentStock,
      minStock,
      barcode,
      imageUrl,
      supplierId
    } = body;

    // Validation
    if (!productCode || !productName || !category || !unit) {
      return NextResponse.json(
        {
          success: false,
          error: 'Code, nom, catégorie et unité sont obligatoires',
        },
        { status: 400 }
      );
    }

    // Vérifier si le code existe déjà
    const existing = await Product.findOne({ productCode });
    if (existing) {
      return NextResponse.json(
        {
          success: false,
          error: `Le code produit "${productCode}" existe déjà`,
        },
        { status: 400 }
      );
    }

    // Créer le produit
    const product = await Product.create({
      productCode,
      productName,
      category,
      subCategory,
      description,
      unit,
      purchasePrice: purchasePrice || 0,
      salePrice: salePrice || 0,
      currentStock: currentStock || 0,
      minStock: minStock || 0,
      barcode,
      imageUrl,
      supplierId: supplierId || null,
      active: true,
    });

    return NextResponse.json({
      success: true,
      message: 'Produit créé avec succès',
      data: product,
    });
  } catch (error) {
    console.error('Erreur API Products POST:', error);
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Erreur lors de la création du produit',
      },
      { status: 500 }
    );
  }
}
