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

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

    console.log('🔍 Testing 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,
      is_active: superAdmin.is_active
    });

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

    console.log(`\n📋 Super Admin Permissions (${permissions.length}):`);
    
    // Check critical permissions
    const criticalPerms = [
      'dashboard.view',
      'settings.access',
      'admin.access',
      'directory.access',
      'conversations.access',
      'profile_page.access'
    ];
    
    console.log('\n🎯 Critical Permissions Check:');
    criticalPerms.forEach(perm => {
      const hasPermission = permissions.some(p => p.name === perm);
      console.log(`  ${hasPermission ? '✅' : '❌'} ${perm}`);
    });

    // Show all permissions
    console.log('\n📝 All Permissions:');
    permissions.forEach((perm, index) => {
      console.log(`  ${index + 1}. ${perm.name}`);
    });

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

testSuperAdminPermissions();
