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

const fixInvoices = async () => {
    try {
        console.log("Finding orders with null invoice_number...");
        // Fetch all orders to be safe and check manually
        const orders = await Order.findAll();

        for (const order of orders) {
            if (!order.invoice_number) {
                const dateStr = new Date(order.createdAt).toISOString().slice(0, 10).replace(/-/g, '');
                const newInvoice = `INV/${dateStr}/OLD${order.id}`;
                console.log(`Updating Order ${order.id} with ${newInvoice}`);

                order.invoice_number = newInvoice;
                await order.save();
            } else {
                console.log(`Order ${order.id} already has invoice: ${order.invoice_number}`);
            }
        }
        console.log("Done.");

    } catch (error) {
        console.error('Error:', error);
    }
};

fixInvoices();
