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

const seedHistory = async () => {
    try {
        // Calculate dates for last month
        const now = new Date();
        const lastMonth = new Date();
        lastMonth.setMonth(now.getMonth() - 1);

        // Fix random days in last month
        const getRandomDateInLastMonth = () => {
            const date = new Date(lastMonth);
            date.setDate(Math.floor(Math.random() * 28) + 1);
            return date;
        };

        console.log("Backdating orders...");

        // Get some orders to update (e.g., half of them)
        const orders = await Order.findAll();

        if (orders.length < 2) {
            console.log("Not enough orders to split. Please seed more data first.");
            return;
        }

        // Move first 2 orders to last month
        const ordersToBackdate = orders.slice(0, 2);

        for (const order of ordersToBackdate) {
            const newDate = getRandomDateInLastMonth();
            order.changed('createdAt', true); // Force update timestamp
            order.createdAt = newDate;
            await order.save({ silent: true }); // silent: true might preserve timestamps depending on sequelize config, but usually we just set it. 
            // Actually sequelize overrides updated_at usually. For createdAt we just set it.
            // Let's use direct update to be sure.
            await sequelize.query(
                `UPDATE orders SET created_at = :date WHERE id = :id`,
                {
                    replacements: { date: newDate, id: order.id },
                    type: sequelize.QueryTypes.UPDATE
                }
            );

            // Also update their items to match
            await sequelize.query(
                `UPDATE order_items SET created_at = :date WHERE order_id = :id`,
                {
                    replacements: { date: newDate, id: order.id },
                    type: sequelize.QueryTypes.UPDATE
                }
            );

            console.log(`Moved Order #${order.id} to ${newDate.toISOString()}`);
        }

        console.log("History seeded! Refresh dashboard to see trends.");

    } catch (error) {
        console.error("Error seeding history:", error);
    } finally {
        await sequelize.close();
    }
};

seedHistory();
