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

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

    console.log('🔍 Testing Super Admin Settings Access...');
    
    // 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
    });

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

    const permissionNames = permissions.map(p => p.name);
    
    // Check critical settings permissions
    const settingsPermissions = [
      'settings.access',
      'settings.profile',
      'settings.security',
      'settings.notifications',
      'settings.privacy',
      'settings.preferences',
      'role.create',
      'role.read',
      'role.update',
      'role.delete',
      'permission.create',
      'permission.read',
      'permission.update',
      'permission.delete',
      'user.manage_roles'
    ];

    console.log('\n🎯 Settings Permissions Check:');
    let allPresent = true;
    settingsPermissions.forEach(perm => {
      const hasPermission = permissionNames.includes(perm);
      console.log(`  ${hasPermission ? '✅' : '❌'} ${perm}`);
      if (!hasPermission) allPresent = false;
    });

    console.log(`\n📊 Total permissions: ${permissionNames.length}`);
    console.log(`🎯 Settings permissions: ${settingsPermissions.length}`);
    console.log(`✅ All settings permissions present: ${allPresent ? 'YES' : 'NO'}`);

    if (allPresent) {
      console.log('\n🎉 Super Admin has FULL ACCESS to Settings page!');
    } else {
      console.log('\n⚠️ Some settings permissions are missing.');
    }

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

testSuperAdminSettingsAccess();
