const UserModel = require('../models/users.model');
const DepositModel = require('../models/deposit.model');
const OrderModel = require('../models/order.model');
const ProductModel = require('../models/product.model');
const moment = require('moment');

class DashboardService {
    async getStats() {
        // 1. Users
        const totalUsers = await UserModel.countDocuments();
        const startOfDay = moment().startOf('day').toDate();
        const newUsersToday = await UserModel.countDocuments({ createdAt: { $gte: startOfDay } });

        // 2. Revenue from Deposits (Real money loaded into system)
        const deposits = await DepositModel.aggregate([
            { $match: { status: 'success' } },
            { $group: { _id: null, total: { $sum: '$receivedAmount' } } },
        ]);
        const totalDepositRevenue = deposits.length ? deposits[0].total : 0;

        // 3. Revenue from Sales (Money spent by users)
        const orders = await OrderModel.aggregate([
            { $match: { status: 'completed' } },
            { $group: { _id: null, total: { $sum: '$price' } } },
        ]);
        const totalSalesRevenue = orders.length ? orders[0].total : 0;

        // 4. Products
        const totalProducts = await ProductModel.countDocuments();
        const soldProducts = await ProductModel.countDocuments({ status: 'sold' });
        const availableProducts = await ProductModel.countDocuments({ status: 'available' });

        // 5. Pending Activities
        const pendingDeposits = await DepositModel.countDocuments({ status: 'pending' });

        return {
            users: {
                total: totalUsers,
                newToday: newUsersToday,
            },
            revenue: {
                deposit: totalDepositRevenue,
                sales: totalSalesRevenue,
            },
            products: {
                total: totalProducts,
                sold: soldProducts,
                available: availableProducts,
            },
            pending: {
                deposits: pendingDeposits,
            },
        };
    }

    async getChartData() {
        // Get last 30 days revenue data
        const thirtyDaysAgo = moment().subtract(30, 'days').startOf('day').toDate();

        const depositChart = await DepositModel.aggregate([
            {
                $match: {
                    status: 'success',
                    createdAt: { $gte: thirtyDaysAgo },
                },
            },
            {
                $group: {
                    _id: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt' } },
                    total: { $sum: '$receivedAmount' },
                },
            },
            { $sort: { _id: 1 } },
        ]);

        const salesChart = await OrderModel.aggregate([
            {
                $match: {
                    status: 'completed',
                    createdAt: { $gte: thirtyDaysAgo },
                },
            },
            {
                $group: {
                    _id: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt' } },
                    total: { $sum: '$price' },
                },
            },
            { $sort: { _id: 1 } },
        ]);

        // Merge data to ensure all days are represented (simplified for now, frontend can handle gaps or we map here)
        // For simplicity, return raw arrays, let frontend merge
        return {
            deposits: depositChart,
            sales: salesChart,
        };
    }

    async getRecentActivities() {
        const recentOrders = await OrderModel.find()
            .sort({ createdAt: -1 })
            .limit(5)
            .populate('userId', 'fullName email')
            .populate('productId', 'title price');

        const recentDeposits = await DepositModel.find()
            .sort({ createdAt: -1 })
            .limit(5)
            .populate('userId', 'fullName email');

        return {
            orders: recentOrders,
            deposits: recentDeposits,
        };
    }
}

module.exports = new DashboardService();
