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

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

    console.log('🔗 Adding missing 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);
    
    // Missing permissions to add
    const missingPermissions = [
      'dashboard.widget.conversations',
      'dashboard.widget.online',
      'dashboard.widget.messages',
      'dashboard.widget.security',
      'security.view'
    ];
    
    for (const permName of missingPermissions) {
      // Check if permission exists
      const [existingPerms] = await connection.execute('SELECT * FROM permissions WHERE name = ?', [permName]);
      
      let permissionId;
      if (existingPerms.length === 0) {
        // Create permission
        const [result] = await connection.execute(
          'INSERT INTO permissions (name, description, resource, action) VALUES (?, ?, ?, ?)',
          [permName, `Permission for ${permName}`, permName.split('.')[0], permName.split('.')[1]]
        );
        permissionId = result.insertId;
        console.log(`✅ Created permission: ${permName}`);
      } else {
        permissionId = existingPerms[0].id;
        console.log(`✅ Permission already exists: ${permName}`);
      }
      
      // Check if role-permission mapping exists
      const [existingMappings] = await connection.execute(
        'SELECT * FROM role_permissions WHERE role_id = ? AND permission_id = ?',
        [superAdminRole.id, permissionId]
      );
      
      if (existingMappings.length === 0) {
        // Create role-permission mapping
        await connection.execute(
          'INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)',
          [superAdminRole.id, permissionId]
        );
        console.log(`✅ Added ${permName} to Super Admin role`);
      } else {
        console.log(`✅ ${permName} already mapped to Super Admin role`);
      }
    }
    
    console.log('\n🎉 All missing permissions added successfully!');
    
    // Verify the additions
    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 = ? AND p.name IN (?)
      ORDER BY p.name
    `, [superAdminRole.id, missingPermissions]);
    
    console.log('\n🔍 Verification - Super Admin now has these permissions:');
    permissions.forEach(p => console.log(`  ✅ ${p.name}`));
    
    await connection.end();
  } catch (error) {
    console.error('❌ Error:', error.message);
  }
}

addMissingSuperAdminPermissions();
