import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { startOfDay, endOfDay, startOfWeek, endOfWeek, startOfMonth, endOfMonth, startOfYear, endOfYear } from 'date-fns'

export async function GET(request: NextRequest) {
  try {
    const now = new Date()
    
    // Time ranges
    const todayStart = startOfDay(now)
    const todayEnd = endOfDay(now)
    const weekStart = startOfWeek(now, { weekStartsOn: 1 })
    const weekEnd = endOfWeek(now, { weekStartsOn: 1 })
    const monthStart = startOfMonth(now)
    const monthEnd = endOfMonth(now)
    const yearStart = startOfYear(now)
    const yearEnd = endOfYear(now)

    // Total sales count
    const [salesToday, salesWeek, salesMonth, salesYear] = await Promise.all([
      db.vente.count({
        where: {
          date: { gte: todayStart, lte: todayEnd },
          statut: 'PAYEE'
        }
      }),
      db.vente.count({
        where: {
          date: { gte: weekStart, lte: weekEnd },
          statut: 'PAYEE'
        }
      }),
      db.vente.count({
        where: {
          date: { gte: monthStart, lte: monthEnd },
          statut: 'PAYEE'
        }
      }),
      db.vente.count({
        where: {
          date: { gte: yearStart, lte: yearEnd },
          statut: 'PAYEE'
        }
      })
    ])

    // Revenue calculations
    const [revenueToday, revenueMonth] = await Promise.all([
      db.vente.aggregate({
        where: {
          date: { gte: todayStart, lte: todayEnd },
          statut: 'PAYEE'
        },
        _sum: {
          montantHT: true,
          montantTTC: true
        }
      }),
      db.vente.aggregate({
        where: {
          date: { gte: monthStart, lte: monthEnd },
          statut: 'PAYEE'
        },
        _sum: {
          montantHT: true,
          montantTTC: true
        }
      })
    ])

    // Total clients
    const totalClients = await db.client.count()

    // Top selling products this month
    const topProducts = await db.ligneVente.groupBy({
      by: ['produitId'],
      where: {
        vente: {
          date: { gte: monthStart, lte: monthEnd },
          statut: 'PAYEE'
        }
      },
      _sum: {
        quantite: true,
        montantTTC: true
      },
      orderBy: {
        _sum: {
          quantite: 'desc'
        }
      },
      take: 5
    })

    // Get product details for top products
    const topProductsWithDetails = await Promise.all(
      topProducts.map(async (item) => {
        const product = await db.produit.findUnique({
          where: { id: item.produitId }
        })
        return {
          designation: product?.designation || 'Inconnu',
          quantity: item._sum.quantite || 0,
          revenue: item._sum.montantTTC || 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,
        stock: true,
        stockMin: true
      },
      orderBy: {
        stock: 'asc'
      },
      take: 10
    })

    // Pending workshop orders (EN_ATTENTE)
    const pendingWorkshopOrders = await db.vente.count({
      where: {
        statut: 'PAYEE',
        statutAtelier: 'EN_ATTENTE'
      }
    })

    const dashboardData = {
      totalSales: {
        today: salesToday,
        week: salesWeek,
        month: salesMonth,
        year: salesYear
      },
      revenue: {
        htToday: revenueToday._sum.montantHT || 0,
        ttcToday: revenueToday._sum.montantTTC || 0,
        htMonth: revenueMonth._sum.montantHT || 0,
        ttcMonth: revenueMonth._sum.montantTTC || 0
      },
      totalClients,
      topProducts: topProductsWithDetails,
      lowStockItems,
      pendingWorkshopOrders
    }

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