const sequelize = require('../config/database');

// Import all models and initialize them with sequelize
const Menu = require('./Menu');
const MenuCategory = require('./MenuCategory');
const Table = require('./Table');
const Client = require('./Client');
const Reservation = require('./Reservation');
const Commande = require('./Commande');
const CommandeItem = require('./CommandeItem');

// Vérifier que tous les modèles sont bien initialisés
console.log('🔍 Checking models initialization:');
console.log('Menu:', !!Menu && typeof Menu.hasMany === 'function');
console.log('MenuCategory:', !!MenuCategory && typeof MenuCategory.hasMany === 'function');
console.log('Table:', !!Table && typeof Table.hasMany === 'function');
console.log('Client:', !!Client && typeof Client.hasMany === 'function');

// Sync database (create tables if they don't exist)
const initDatabase = async () => {
    try {
        await sequelize.authenticate();
        console.log('✅ Database connection established successfully.');
        
        // Sync all models
        await sequelize.sync({ alter: true });
        console.log('✅ All models synchronized successfully.');
        
    } catch (error) {
        console.error('❌ Unable to connect to the database:', error);
    }
};

// Define associations only after models are properly initialized
const defineAssociations = () => {
    try {
        console.log('🔗 Defining associations...');
        
        // Vérifier que MenuCategory est bien un modèle Sequelize
        if (!MenuCategory || typeof MenuCategory.hasMany !== 'function') {
            console.error('❌ MenuCategory is not a valid Sequelize model');
            console.log('MenuCategory type:', typeof MenuCategory);
            console.log('MenuCategory methods:', MenuCategory ? Object.getOwnPropertyNames(MenuCategory) : 'undefined');
            return;
        }

        // Menu associations
        MenuCategory.hasMany(Menu, {
            foreignKey: 'categorie_id',
            as: 'menus'
        });

        Menu.belongsTo(MenuCategory, {
            foreignKey: 'categorie_id',
            as: 'category'
        });

        // Client associations
        if (Client && typeof Client.hasMany === 'function') {
            // Client.hasMany(Reservation, {
            //     foreignKey: 'client_id',
            //     as: 'reservations'
            // });

            // Client.hasMany(Commande, {
            //     foreignKey: 'client_id',
            //     as: 'commandes'
            // });
        }

        // Table associations
        if (Table && typeof Table.hasMany === 'function') {
            // Table.hasMany(Reservation, {
            //     foreignKey: 'table_id',
            //     as: 'reservations'
            // });

            // Table.hasMany(Commande, {
            //     foreignKey: 'table_id',
            //     as: 'commandes'
            // });
        }

        // Reservation associations
        if (Reservation && typeof Reservation.belongsTo === 'function') {
            Reservation.belongsTo(Client, {
                foreignKey: 'client_id',
                as: 'client'
            });

            Reservation.belongsTo(Table, {
                foreignKey: 'table_id',
                as: 'table'
            });

            Reservation.hasMany(Commande, {
                foreignKey: 'reservation_id',
                as: 'commandes'
            });
        }

        // // Order associations
        // if (Commande && typeof Commande.belongsTo === 'function') {
        //     Commande.belongsTo(Client, {
        //         foreignKey: 'client_id',
        //         as: 'client'
        //     });

        //     Commande.belongsTo(Table, {
        //         foreignKey: 'table_id',
        //         as: 'table'
        //     });

        //     Commande.belongsTo(Reservation, {
        //         foreignKey: 'reservation_id',
        //         as: 'reservation'
        //     });

        //     Commande.hasMany(CommandeItem, {
        //         foreignKey: 'commande_id',
        //         as: 'items'
        //     });
        // }

        // Order item associations
        if (CommandeItem && typeof CommandeItem.belongsTo === 'function') {
            CommandeItem.belongsTo(Commande, {
                foreignKey: 'commande_id',
                as: 'commande'
            });

            CommandeItem.belongsTo(Menu, {
                foreignKey: 'menu_id',
                as: 'menu'
            });
        }

     

    if (Reservation) {
    //   Reservation.hasMany(Commande, { foreignKey: 'reservation_id', as: 'commandes' });
    //   Commande.belongsTo(Reservation, { foreignKey: 'reservation_id', as: 'reservation' });
    }

        console.log('✅ All associations defined successfully');
        
    } catch (error) {
        console.error('❌ Error defining associations:', error);
    }
};

// Initialize associations
defineAssociations();

module.exports = {
    sequelize,
    Menu,
    MenuCategory,
    Table,
    Client,
    Reservation,
    Commande,
    CommandeItem,
    initDatabase
};
