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

export async function GET(request: NextRequest) {
  try {
    const lowStockItems = await db.produit.findMany({
      where: {
        actif: true,
        stock: {
          lt: db.produit.fields.stockMin
        }
      },
      include: {
        fournisseur: {
          select: {
            nom: true
          }
        }
      },
      orderBy: {
        stock: 'asc'
      }
    })

    const headers = [
      'Référence',
      'Désignation',
      'Catégorie',
      'Marque',
      'Fournisseur',
      'Stock actuel',
      'Stock minimum',
      'Déficit',
      'Prix achat HT',
      'Valeur à commander',
      'Emplacement',
      'Code barre'
    ]

    const rows = lowStockItems.map((product) => {
      const deficit = product.stockMin - product.stock
      const orderValue = deficit * product.prixAchatHT

      return [
        product.reference,
        `"${product.designation}"`,
        product.categorie,
        product.marque || '',
        product.fournisseur?.nom || '',
        product.stock.toString(),
        product.stockMin.toString(),
        deficit.toString(),
        product.prixAchatHT.toFixed(2),
        orderValue.toFixed(2),
        product.emplacement || '',
        product.codeBarre || ''
      ].join(',')
    })

    const csvContent = [headers.join(','), ...rows].join('\n')

    return new NextResponse(csvContent, {
      headers: {
        'Content-Type': 'text/csv; charset=utf-8',
        'Content-Disposition': 'attachment; filename="stock_faible.csv"'
      }
    })
  } catch (error) {
    console.error('Error exporting low stock data:', error)
    return NextResponse.json(
      { error: 'Failed to export low stock data' },
      { status: 500 }
    )
  }
}
