const mysql = require('mysql2/promise');

async function debugSuperAdminPermissions() {
  try {
    const connection = await mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: '',
      database: 'cms_db'
    });

    console.log('🔍 Debugging Super Admin Permissions...');
    
    // Get Super Admin user
    const [users] = await connection.execute('SELECT * FROM users WHERE role_id = 1 LIMIT 1');
    if (users.length === 0) {
      console.log('❌ No Super Admin user found');
      return;
    }

    const superAdmin = users[0];
    console.log('✅ Super Admin user found:', {
      id: superAdmin.id,
      name: superAdmin.name,
      email: superAdmin.email,
      role_id: superAdmin.role_id,
      role: superAdmin.role
    });

    // Get Super Admin role details
    const [roles] = await connection.execute('SELECT * FROM roles WHERE id = ?', [superAdmin.role_id]);
    const role = roles[0];
    console.log('✅ Super Admin role:', {
      id: role.id,
      name: role.name,
      level: role.level,
      is_active: role.is_active
    });

    // Get all permissions for Super Admin
    const [permissions] = await connection.execute(`
      SELECT p.id, p.name, p.description, p.resource, p.action
      FROM permissions p 
      JOIN role_permissions rp ON p.id = rp.permission_id 
      WHERE rp.role_id = ?
      ORDER BY p.name
    `, [superAdmin.role_id]);

    console.log(`\n📊 Super Admin has ${permissions.length} permissions:`);
    
    // Group permissions by resource
    const permissionsByResource = {};
    permissions.forEach(p => {
      if (!permissionsByResource[p.resource]) {
        permissionsByResource[p.resource] = [];
      }
      permissionsByResource[p.resource].push(p.name);
    });

    Object.keys(permissionsByResource).sort().forEach(resource => {
      console.log(`\n📁 ${resource.toUpperCase()}:`);
      permissionsByResource[resource].forEach(perm => {
        console.log(`  ✅ ${perm}`);
      });
    });

    // Check specific settings permissions
    const settingsPermissions = [
      'settings.access',
      'settings.profile', 
      'settings.security',
      'settings.notifications',
      'settings.privacy',
      'settings.preferences'
    ];

    console.log('\n🎯 Settings Permissions Check:');
    settingsPermissions.forEach(perm => {
      const hasPermission = permissions.some(p => p.name === perm);
      console.log(`  ${hasPermission ? '✅' : '❌'} ${perm}`);
    });

    // Check if user has any role_id issues
    console.log('\n🔍 User Role Check:');
    console.log(`  User role_id: ${superAdmin.role_id}`);
    console.log(`  Role name: ${role.name}`);
    console.log(`  Role level: ${role.level}`);

    await connection.end();
  } catch (error) {
    console.error('❌ Error:', error.message);
  }
}

debugSuperAdminPermissions();
