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

export async function GET(request: NextRequest) {
  try {
    // Stock valuation by category
    const stockValuationRaw = await db.produit.groupBy({
      by: ['categorie'],
      where: {
        actif: true
      },
      _sum: {
        stock: true
      },
      _count: true
    })

    // Calculate value for each category
    const stockValuationByCategory = await Promise.all(
      stockValuationRaw.map(async (item) => {
        const products = await db.produit.findMany({
          where: {
            categorie: item.categorie,
            actif: true
          },
          select: {
            stock: true,
            prixAchatHT: true
          }
        })

        const totalValue = products.reduce((sum, p) => sum + (p.stock * p.prixAchatHT), 0)

        return {
          category: item.categorie,
          value: totalValue,
          count: item._count
        }
      })
    )

    const totalValue = stockValuationByCategory.reduce((sum, item) => sum + item.value, 0)

    // Low stock items
    const lowStockItems = await db.produit.findMany({
      where: {
        actif: true,
        stock: {
          lt: db.produit.fields.stockMin
        }
      },
      select: {
        id: true,
        reference: true,
        designation: true,
        categorie: true,
        stock: true,
        stockMin: true,
        prixAchatHT: true
      },
      orderBy: {
        stock: 'asc'
      }
    })

    const lowStockItemsWithValue = lowStockItems.map((item) => ({
      ...item,
      value: item.stock * item.prixAchatHT
    }))

    // Category breakdown
    const categoryBreakdown = await Promise.all(
      ['MONTURE', 'VERRE', 'LENTILLE', 'ACCESSOIRE'].map(async (category) => {
        const [totalProducts, activeProducts] = await Promise.all([
          db.produit.count({ where: { categorie: category } }),
          db.produit.count({ where: { categorie: category, actif: true } })
        ])

        const products = await db.produit.findMany({
          where: { categorie: category, actif: true },
          select: { stock: true, prixAchatHT: true }
        })

        const totalStock = products.reduce((sum, p) => sum + p.stock, 0)
        const stockValue = products.reduce((sum, p) => sum + (p.stock * p.prixAchatHT), 0)

        return {
          category,
          totalProducts,
          activeProducts,
          totalStock,
          stockValue
        }
      })
    )

    const inventoryData = {
      stockValuation: {
        totalValue,
        byCategory: stockValuationByCategory
      },
      lowStockItems: lowStockItemsWithValue,
      categoryBreakdown
    }

    return NextResponse.json(inventoryData)
  } catch (error) {
    console.error('Error fetching inventory data:', error)
    return NextResponse.json(
      { error: 'Failed to fetch inventory data' },
      { status: 500 }
    )
  }
}
