
import db from '../src/database/models/index.js';
import { ROLES } from '../src/common/config/constants.js';

async function diagnoseZBH() {
    try {
        console.log('--- Diagnosis Start ---');
        
        // 1. Check Role table
        const roles = await db.Role.findAll();
        console.log('Available Roles:');
        roles.forEach(r => console.log(`- ID: ${r.id}, Code: ${r.roleCode}, Name: ${r.roleName}`));
        
        const zbhRole = await db.Role.findOne({ 
            where: { 
                [db.Sequelize.Op.or]: [
                    { roleCode: ROLES.ZBH },
                    { roleName: { [db.Sequelize.Op.iLike]: '%Zonal Business Head%' } },
                    { roleName: { [db.Sequelize.Op.iLike]: '%Zone Business Head%' } }
                ]
            } 
        });
        
        if (zbhRole) {
            console.log(`\nIdentified ZBH Role: ID=${zbhRole.id}, Code=${zbhRole.roleCode}`);
        } else {
            console.error('\nFAILED to identify ZBH Role using current logic!');
        }

        // 2. Check Zones
        const zones = await db.Zone.findAll({
            include: [{ model: db.User, as: 'zonalBusinessHead' }]
        });
        console.log('\nZones Status:');
        zones.forEach(z => {
            console.log(`- Zone: ${z.name} (ID: ${z.id})`);
            console.log(`  zbhId (Zone table): ${z.zbhId}`);
            console.log(`  zbhCode (Zone table): ${z.zbhCode}`);
            console.log(`  zonalBusinessHead (Association): ${z.zonalBusinessHead ? z.zonalBusinessHead.fullName : 'None'}`);
        });

        // 3. Check UserRoles for ZBH
        if (zbhRole) {
            const zbhAssignments = await db.UserRole.findAll({
                where: { roleId: zbhRole.id, isActive: true },
                include: [
                    { model: db.User, as: 'user' },
                    { model: db.Zone, as: 'zone' }
                ]
            });
            console.log('\nActive ZBH UserRole Assignments:');
            zbhAssignments.forEach(a => {
                console.log(`- User: ${a.user.fullName} (ID: ${a.userId}) -> Zone: ${a.zone?.name || 'NULL'} (ID: ${a.zoneId})`);
            });
        }

        console.log('\n--- Diagnosis End ---');
        process.exit(0);
    } catch (error) {
        console.error('Diagnosis Failed:', error);
        process.exit(1);
    }
}

diagnoseZBH();
