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

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

    console.log('🔗 Checking Super Admin permissions...');
    
    // Get Super Admin role
    const [roles] = await connection.execute('SELECT * FROM roles WHERE name = ?', ['Super Admin']);
    if (roles.length === 0) {
      console.log('❌ Super Admin role not found');
      return;
    }
    
    const superAdminRole = roles[0];
    console.log('✅ Super Admin role found:', superAdminRole);
    
    // Get all permissions for Super Admin
    const [permissions] = await connection.execute(`
      SELECT p.name, p.description 
      FROM permissions p 
      JOIN role_permissions rp ON p.id = rp.permission_id 
      WHERE rp.role_id = ?
      ORDER BY p.name
    `, [superAdminRole.id]);
    
    console.log(`\n📊 Super Admin has ${permissions.length} permissions:`);
    permissions.forEach(p => console.log(`  ✅ ${p.name}`));
    
    // Check specific dashboard permissions
    const dashboardPermissions = permissions.filter(p => p.name.includes('dashboard'));
    console.log(`\n🎯 Dashboard permissions (${dashboardPermissions.length}):`);
    dashboardPermissions.forEach(p => console.log(`  ✅ ${p.name}`));
    
    // Check critical permissions
    const criticalPermissions = [
      'dashboard.view',
      'dashboard.analytics',
      'dashboard.widget.contacts',
      'dashboard.widget.conversations',
      'dashboard.widget.online',
      'dashboard.widget.messages',
      'dashboard.widget.security',
      'user.manage_roles',
      'user.read',
      'audit_log.read',
      'security.view',
      'conversation.read',
      'message.read',
      'message.create',
      'conversation.create',
      'system_settings.read'
    ];
    
    console.log(`\n🔑 Critical permissions check:`);
    criticalPermissions.forEach(perm => {
      const hasPermission = permissions.some(p => p.name === perm);
      console.log(`  ${hasPermission ? '✅' : '❌'} ${perm}`);
    });
    
    await connection.end();
  } catch (error) {
    console.error('❌ Error:', error.message);
  }
}

checkSuperAdminPermissions();
