const { catchAsyncErrors } = require('../../middlewares/catchAsyncErrors');
const ErrorHandler = require('../../utils/ErrorHandler');
const dashboardService = require('../../services/dashboard.service');

/**
 * GET /super/dashboard
 * Unified Dashboard API - Get all dashboard data in one call
 */
exports.getFullDashboard = catchAsyncErrors(async (req, res, next) => {
    const { topLimit = 10, startDate, endDate } = req.query;

    // Fetch all data in parallel for better performance
    const [stats, topVendors, topUsers, zoneSalesResult] = await Promise.all([
        dashboardService.getDashboardStats(),
        dashboardService.getTopVendorsSuperAdmin(topLimit, req.query.zone),
        dashboardService.getTopUsersSuperAdmin(topLimit),
        dashboardService.getZoneWiseSales({ startDate, endDate }),
    ]);

    res.status(200).json({
        success: true,
        data: {
            stats,
            topVendors,
            topUsers,
            zoneSales: zoneSalesResult.zoneSales,
            zoneSalesSummary: zoneSalesResult.summary,
        }
    });
});

/**
 * GET /super/dashboard/stats
 * Dashboard statistics only
 */
exports.getDashboardStats = catchAsyncErrors(async (req, res, next) => {
    const stats = await dashboardService.getDashboardStats();
    res.status(200).json({ success: true, stats });
});

/**
 * GET /super/dashboard/top-vendors
 * Top vendors by completed bookings and revenue
 */
exports.getTopVendors = catchAsyncErrors(async (req, res, next) => {
    const { limit = 10, zone } = req.query;
    const topVendors = await dashboardService.getTopVendorsSuperAdmin(limit, zone);
    res.status(200).json({ success: true, topVendors });
});

/**
 * GET /super/dashboard/top-users
 * Top users by booking count
 */
exports.getTopUsers = catchAsyncErrors(async (req, res, next) => {
    const { limit = 10 } = req.query;
    const topUsers = await dashboardService.getTopUsersSuperAdmin(limit);
    res.status(200).json({ success: true, topUsers });
});

/**
 * GET /super/dashboard/zone-sales
 * Zone-wise sales breakdown
 */
exports.getZoneWiseSales = catchAsyncErrors(async (req, res, next) => {
    const { startDate, endDate } = req.query;
    const result = await dashboardService.getZoneWiseSales({ startDate, endDate });
    res.status(200).json({ success: true, zoneSales: result.zoneSales, summary: result.summary });
});

/**
 * GET /super/dashboard/live-orders
 * Real-time active orders
 */
exports.getLiveOrders = catchAsyncErrors(async (req, res, next) => {
    const { limit = 20 } = req.query;
    const result = await dashboardService.getLiveOrdersSuperAdmin(limit);
    res.status(200).json({ success: true, liveOrders: result.liveOrders, counts: result.counts });
});

/**
 * GET /super/dashboard/sales-summary
 * Sales summary with daily, weekly, or monthly breakdown
 */
exports.getSalesSummary = catchAsyncErrors(async (req, res, next) => {
    const { period = 'daily' } = req.query;

    // Validate period
    const validPeriods = ['daily', 'weekly', 'monthly'];
    if (!validPeriods.includes(period)) {
        return next(new ErrorHandler('Invalid period. Use: daily, weekly, or monthly', 400));
    }

    const result = await dashboardService.getSalesSummary(period);
    res.status(200).json({ success: true, ...result });
});
