const { sequelize, Order, OrderItem } = require('./models');
const { Op } = require('sequelize');

const testAnalytics = async () => {
    try {
        const revenueStatus = ['paid', 'shipped', 'delivered', 'completed'];

        const now = new Date();
        const startCurrentMonth = new Date(now.getFullYear(), now.getMonth(), 1);
        const startLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        const endLastMonth = new Date(now.getFullYear(), now.getMonth(), 0);

        console.log("Start Current Month:", startCurrentMonth);
        console.log("Start Last Month:", startLastMonth);
        console.log("End Last Month:", endLastMonth);

        // Revenue Current
        const revenueCurrentMonth = await Order.sum('total_amount', {
            where: {
                status: { [Op.in]: revenueStatus },
                createdAt: { [Op.gte]: startCurrentMonth }
            }
        }) || 0;

        console.log("Revenue Current:", revenueCurrentMonth);

        // Revenue Last Month
        const revenueLastMonth = await Order.sum('total_amount', {
            where: {
                status: { [Op.in]: revenueStatus },
                createdAt: {
                    [Op.between]: [startLastMonth, endLastMonth]
                }
            }
        }) || 0;

        console.log("Revenue Last Month:", revenueLastMonth);

        const calculateChange = (current, previous) => {
            if (previous === 0) return current > 0 ? "+ 100%" : "0%";
            const percent = ((current - previous) / previous) * 100;
            return `${percent >= 0 ? "+ " : ""}${percent.toFixed(1)}%`;
        };

        console.log("Change:", calculateChange(revenueCurrentMonth, revenueLastMonth));

        // Debug Query for Last Month
        const ordersLastMonth = await Order.findAll({
            where: {
                status: { [Op.in]: revenueStatus },
                createdAt: {
                    [Op.between]: [startLastMonth, endLastMonth]
                }
            }
        });
        console.log("Orders found in Last Month range:", ordersLastMonth.length);
        ordersLastMonth.forEach(o => console.log(` - Order #${o.id} Date: ${o.createdAt}`));

    } catch (error) {
        console.error("Error:", error);
    } finally {
        // await sequelize.close(); // keep open or close? defaults to close on process exit usually
        process.exit();
    }
};

testAnalytics();
