import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import prisma from '@/lib/prisma'
import { authOptions } from '@/lib/auth'

export const dynamic = 'force-dynamic'

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (session?.user?.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }

    const now = new Date()
    const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
    const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
    const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())

    const [
      totalUsers,
      totalOrders,
      totalRevenue,
      pendingOrders,
      todayOrders,
      todayRevenue,
      weeklyRevenue,
      recentOrders,
      orderStatusCounts,
    ] = await Promise.all([
      prisma.user.count({ where: { role: 'USER' } }),
      prisma.order.count(),
      prisma.order.aggregate({
        where: { status: 'SUCCESS' },
        _sum: { price: true },
      }),
      prisma.order.count({ where: { status: 'PENDING' } }),
      prisma.order.count({ where: { createdAt: { gte: todayStart } } }),
      prisma.order.aggregate({
        where: { status: 'SUCCESS', createdAt: { gte: todayStart } },
        _sum: { price: true },
      }),
      prisma.order.aggregate({
        where: { status: 'SUCCESS', createdAt: { gte: sevenDaysAgo } },
        _sum: { price: true },
      }),
      prisma.order.findMany({
        take: 10,
        orderBy: { createdAt: 'desc' },
        include: {
          user: { select: { name: true, email: true } },
          vipProduct: { select: { gameName: true, productName: true } },
          digitalProduct: { select: { name: true } },
          smmProduct: { select: { name: true } },
        },
      }),
      prisma.order.groupBy({
        by: ['status'],
        _count: { status: true },
      }),
    ])

    // Daily revenue for chart (last 7 days)
    const dailyRevenue = await Promise.all(
      Array.from({ length: 7 }, (_, i) => {
        const date = new Date(now)
        date.setDate(date.getDate() - (6 - i))
        const start = new Date(date.getFullYear(), date.getMonth(), date.getDate())
        const end = new Date(start.getTime() + 24 * 60 * 60 * 1000)
        return prisma.order
          .aggregate({
            where: { status: 'SUCCESS', createdAt: { gte: start, lt: end } },
            _sum: { price: true },
          })
          .then((r) => ({
            date: start.toLocaleDateString('id-ID', { day: 'numeric', month: 'short' }),
            revenue: Number(r._sum.price || 0),
          }))
      })
    )

    return NextResponse.json({
      stats: {
        totalUsers,
        totalOrders,
        totalRevenue: Number(totalRevenue._sum.price || 0),
        pendingOrders,
        todayOrders,
        todayRevenue: Number(todayRevenue._sum.price || 0),
        weeklyRevenue: Number(weeklyRevenue._sum.price || 0),
      },
      orderStatusCounts: Object.fromEntries(
        orderStatusCounts.map((s) => [s.status, s._count.status])
      ),
      recentOrders,
      dailyRevenue,
    })
  } catch (error) {
    console.error('[ADMIN STATS]', error)
    return NextResponse.json({ error: 'Gagal memuat statistik' }, { status: 500 })
  }
}
