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

const migrate = async () => {
    try {
        await sequelize.authenticate();
        console.log('Connection has been established successfully.');

        // This will alter the table to add the new column
        await Order.sync({ alter: true });
        console.log('Order table synced successfully.');

        // Optional: Backfill existing orders
        const orders = await Order.findAll({ where: { invoice_number: null } });
        for (const order of orders) {
            order.invoice_number = `INV/${new Date(order.created_at).toISOString().slice(0, 10).replace(/-/g, '')}/OLD${order.id}`;
            await order.save();
            console.log(`Updated order ${order.id} with invoice ${order.invoice_number}`);
        }

    } catch (error) {
        console.error('Unable to connect to the database:', error);
    } finally {
        await sequelize.close();
    }
};

migrate();
