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

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

    const headers = [
      'Référence',
      'Désignation',
      'Catégorie',
      'Marque',
      'Fournisseur',
      'Stock actuel',
      'Stock minimum',
      'Prix achat HT',
      'Prix vente TTC',
      'TVA %',
      'Valeur stock HT',
      'Emplacement',
      'Code barre',
      'Statut stock'
    ]

    const rows = products.map((product) => {
      const stockValue = product.stock * product.prixAchatHT
      const stockStatus = product.stock < product.stockMin ? 'FAIBLE' : 'OK'

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

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

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