import { NextRequest, NextResponse } from 'next/server' import { withAdminAuth } from '@/lib/admin-middleware' import { connectDB } from '@/lib/mongodb' import { User } from '@/models/user' import { Transaction } from '@/models/transaction' import { Billing } from '@/models/billing' import { DeveloperRequest } from '@/models/developer-request' export async function GET(request: NextRequest) { return withAdminAuth(request, async (req, admin) => { try { await connectDB() // Get current date for time-based queries const now = new Date() const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1) const startOfWeek = new Date(now.setDate(now.getDate() - now.getDay())) const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate()) // User statistics const totalUsers = await User.countDocuments() const activeUsers = await User.countDocuments({ lastLogin: { $gte: startOfMonth } }) const newUsersThisMonth = await User.countDocuments({ createdAt: { $gte: startOfMonth } }) const verifiedUsers = await User.countDocuments({ isVerified: true }) // Financial statistics const totalRevenue = await Billing.aggregate([ { $group: { _id: null, total: { $sum: '$amount' } } }, ]) const monthlyRevenue = await Billing.aggregate([ { $match: { created_at: { $gte: startOfMonth } } }, { $group: { _id: null, total: { $sum: '$amount' } } }, ]) const weeklyRevenue = await Billing.aggregate([ { $match: { created_at: { $gte: startOfWeek } } }, { $group: { _id: null, total: { $sum: '$amount' } } }, ]) // Transaction statistics const totalTransactions = await Transaction.countDocuments() const monthlyTransactions = await Transaction.countDocuments({ createdAt: { $gte: startOfMonth }, }) // Service statistics const totalServices = await Billing.countDocuments() const activeServices = await Billing.countDocuments({ payment_status: 'paid', service_status: 1, // 1 = active }) // Developer requests const totalDeveloperRequests = await DeveloperRequest.countDocuments() const pendingDeveloperRequests = await DeveloperRequest.countDocuments({ status: 'pending', }) // Recent activity (last 7 days) const recentUsers = await User.find({ createdAt: { $gte: startOfWeek } }) .select('name email siliconId createdAt') .sort({ createdAt: -1 }) .limit(10) const recentTransactions = await Transaction.find({ createdAt: { $gte: startOfWeek } }) .populate('userId', 'name email siliconId') .sort({ createdAt: -1 }) .limit(10) // Service breakdown const serviceBreakdown = await Billing.aggregate([ { $group: { _id: '$service_type', count: { $sum: 1 }, revenue: { $sum: '$amount' }, }, }, { $sort: { count: -1 } }, ]) // Monthly growth data (last 6 months) const sixMonthsAgo = new Date() sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6) const monthlyGrowth = await User.aggregate([ { $match: { createdAt: { $gte: sixMonthsAgo } } }, { $group: { _id: { year: { $year: '$createdAt' }, month: { $month: '$createdAt' }, }, count: { $sum: 1 }, }, }, { $sort: { '_id.year': 1, '_id.month': 1 } }, ]) const revenueGrowth = await Billing.aggregate([ { $match: { created_at: { $gte: sixMonthsAgo } } }, { $group: { _id: { year: { $year: '$created_at' }, month: { $month: '$created_at' }, }, revenue: { $sum: '$amount' }, }, }, { $sort: { '_id.year': 1, '_id.month': 1 } }, ]) return NextResponse.json({ users: { total: totalUsers, active: activeUsers, newThisMonth: newUsersThisMonth, verified: verifiedUsers, verificationRate: totalUsers > 0 ? ((verifiedUsers / totalUsers) * 100).toFixed(1) : 0, }, revenue: { total: totalRevenue[0]?.total || 0, monthly: monthlyRevenue[0]?.total || 0, weekly: weeklyRevenue[0]?.total || 0, }, transactions: { total: totalTransactions, monthly: monthlyTransactions, }, services: { total: totalServices, active: activeServices, breakdown: serviceBreakdown, }, developerRequests: { total: totalDeveloperRequests, pending: pendingDeveloperRequests, }, recentActivity: { users: recentUsers, transactions: recentTransactions, }, growth: { users: monthlyGrowth, revenue: revenueGrowth, }, }) } catch (error) { console.error('Admin dashboard error:', error) return NextResponse.json({ error: 'Failed to fetch dashboard data' }, { status: 500 }) } }) }