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

console.log("Using exported Sequelize instance.");

async function runDebug() {
    try {
        await sequelize.authenticate();
        console.log('Connection has been established successfully.');

        console.log("\n--- DEBUGGING SPECIFIC FIND BY PK (ID: 3) ---");
        try {
            const fullOrder = await Order.findByPk(3, {
                include: [
                    {
                        model: OrderItem,
                        include: [Book]
                    },
                    {
                        model: User,
                        attributes: ['id', 'name', 'email', 'phone']
                    }
                ]
            });

            if (fullOrder) {
                console.log("SUCCESS: Order 3 found!");
                console.log("Order User:", fullOrder.User ? fullOrder.User.name : "No User Associated");
                console.log("Order Items:", fullOrder.OrderItems ? fullOrder.OrderItems.length : 0);
                if (fullOrder.OrderItems && fullOrder.OrderItems.length > 0) {
                    console.log("First Item Book:", fullOrder.OrderItems[0].Book ? fullOrder.OrderItems[0].Book.title : "No Book");
                }
            } else {
                console.log("FAILURE: Order 3 NOT found via findByPk.");
            }
        } catch (e) {
            console.error("CRITICAL ERROR during findByPk:", e);
        }

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

runDebug();
