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

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

  try {
    console.log('🔍 Checking Super Admin Permissions...\n');

    // Check Super Admin user
    const [users] = await connection.execute(`
      SELECT u.id, u.name, r.name as role_name, u.role_id 
      FROM users u
      JOIN roles r ON u.role_id = r.id
      WHERE r.name = 'Super Admin' OR r.name = 'Super_admin'
    `);
    
    console.log('👤 Super Admin Users:', users);

    if (users.length > 0) {
      const superAdmin = users[0];
      
      // Check user permissions
      const [userPermissions] = await connection.execute(`
        SELECT p.name as permission_name
        FROM user_permissions up
        JOIN permissions p ON up.permission_id = p.id
        WHERE up.user_id = ?
      `, [superAdmin.id]);
      
      console.log('\n🔑 User-specific Permissions:', userPermissions.map(p => p.permission_name));

      // Check role permissions
      const [rolePermissions] = await connection.execute(`
        SELECT p.name as permission_name
        FROM role_permissions rp
        JOIN permissions p ON rp.permission_id = p.id
        WHERE rp.role_id = ?
      `, [superAdmin.role_id]);
      
      console.log('\n🎭 Role Permissions:', rolePermissions.map(p => p.permission_name));

      // Check directory-related permissions
      const [directoryPermissions] = await connection.execute(`
        SELECT p.name as permission_name
        FROM permissions p
        WHERE p.name LIKE '%directory%' OR p.name LIKE '%contact%' OR p.name LIKE '%user%'
        ORDER BY p.name
      `);
      
      console.log('\n📁 Available Directory Permissions:', directoryPermissions.map(p => p.permission_name));

      // Check if Super Admin has directory permissions
      const allPermissions = [...userPermissions, ...rolePermissions].map(p => p.permission_name);
      const directoryPerms = directoryPermissions.map(p => p.permission_name);
      
      const hasDirectoryAccess = allPermissions.some(p => 
        p === 'directory.access' || p === 'contact.read' || p === 'user.read'
      );
      
      console.log('\n✅ Super Admin Directory Access:', hasDirectoryAccess);
      
      if (!hasDirectoryAccess) {
        console.log('\n❌ Super Admin missing directory permissions!');
        console.log('🔧 Adding missing permissions...');
        
        // Add directory permissions to Super Admin role
        const permissionsToAdd = [
          'directory.access',
          'contact.read', 
          'user.read',
          'directory.grid_view',
          'directory.tree_view',
          'directory.filters',
          'directory.search',
          'directory.unit_filter',
          'directory.department_filter',
          'unit.create',
          'user.create',
          'department.create',
          'user.delete',
          'contact.delete',
          'department.delete',
          'user.excel_upload',
          'user.manage_roles',
          'admin.access',
          'super_admin.access'
        ];
        
        for (const permName of permissionsToAdd) {
          try {
            // Get permission ID
            const [permResult] = await connection.execute(
              'SELECT id FROM permissions WHERE name = ?',
              [permName]
            );
            
            if (permResult.length > 0) {
              const permId = permResult[0].id;
              
              // Check if role already has this permission
              const [existing] = await connection.execute(
                'SELECT id FROM role_permissions WHERE role_id = ? AND permission_id = ?',
                [superAdmin.role_id, permId]
              );
              
              if (existing.length === 0) {
                await connection.execute(
                  'INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)',
                  [superAdmin.role_id, permId]
                );
                console.log(`✅ Added ${permName} to Super Admin role`);
              } else {
                console.log(`⚠️ ${permName} already exists for Super Admin role`);
              }
            } else {
              console.log(`❌ Permission ${permName} not found in database`);
            }
          } catch (error) {
            console.log(`❌ Error adding ${permName}:`, error.message);
          }
        }
      }
    }

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

checkSuperAdminPermissions();
