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

const generateId = (prefix) => {
    const date = new Date();
    // Use slightly different times for each to ensure uniqueness if needed, or just random
    // Add random seconds to date to vary inputs
    date.setSeconds(date.getSeconds() + Math.floor(Math.random() * 10000));

    const dateStr = date.toISOString().slice(0, 10).replace(/-/g, ''); // YYYYMMDD
    const timeStr = date.toTimeString().slice(0, 4).replace(/:/g, ''); // HHMM
    const randomStr = Math.random().toString(36).substring(2, 6).toUpperCase();
    return `${prefix}/${dateStr}-${timeStr}/${randomStr}`;
};

const resetAndSeedOrders = async () => {
    try {
        await sequelize.authenticate();
        console.log('Database connected.');

        // Sync schema to ensure order_number column exists
        await Order.sync({ alter: true });
        await OrderItem.sync({ alter: true });
        console.log('Order schema synced.');

        // 1. Clear existing Orders and OrderItems
        // We use truncate with cascade if supported, or just destroy all
        await OrderItem.destroy({ where: {}, truncate: false }); // SQLite/MySQL safety
        await Order.destroy({ where: {}, truncate: false });
        console.log('Old orders cleared.');

        // 2. Fetch Users and Books
        const users = await User.findAll();
        const books = await Book.findAll();

        if (users.length < 2 || books.length < 5) {
            console.error('Not enough users or books to seed orders. Run main seed.js first.');
            process.exit(1);
        }

        // 3. Create Orders
        const ordersData = [
            {
                userIndex: 1, // John Doe
                status: 'paid',
                items: [0, 1], // Book indices
                method: 'QRIS'
            },
            {
                userIndex: 2, // Jane Doe
                status: 'shipped',
                items: [5], // Atomic Habits
                qty: [2],
                method: 'Transfer Bank'
            },
            {
                userIndex: 3, // Budi
                status: 'pending',
                items: [2],
                method: 'QRIS'
            },
            {
                userIndex: 1, // John Doe again
                status: 'completed',
                items: [3, 4],
                method: 'E-Wallet'
            },
            {
                userIndex: 0, // Admin (cancelled)
                status: 'cancelled',
                items: [10],
                method: 'COD'
            }
        ];

        for (const data of ordersData) {
            const user = users[data.userIndex];
            if (!user) continue;

            let total = 0;
            const orderItemsReq = [];

            // Calculate total and prepare items
            for (let i = 0; i < data.items.length; i++) {
                const bookIndex = data.items[i];
                const book = books[bookIndex];
                const qty = data.qty ? data.qty[i] : 1;

                if (book) {
                    total += Number(book.price) * qty;
                    orderItemsReq.push({
                        book_id: book.id,
                        quantity: qty,
                        price: book.price
                    });
                }
            }

            const invNum = generateId('INV');
            const ordNum = generateId('ORD');

            const order = await Order.create({
                user_id: user.id,
                total_amount: total,
                status: data.status,
                invoice_number: invNum,
                order_number: ordNum,
                payment_method: data.method,
                shipping_address: user.address || 'Alamat Default'
            });

            for (const item of orderItemsReq) {
                await OrderItem.create({
                    order_id: order.id,
                    ...item
                });
            }
            console.log(`Created Order #${order.id} | INV: ${invNum} | ORD: ${ordNum}`);
        }

        console.log('Orders Reset and Reseeded Successfully!');
        process.exit(0);
    } catch (error) {
        console.error('Failed to reset orders:', error);
        process.exit(1);
    }
};

resetAndSeedOrders();
