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

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

    console.log('🔧 Fixing role-permission mappings...');
    
    // Get permission IDs
    const [permissions] = await connection.execute(`
      SELECT id, name FROM permissions 
      WHERE name IN (
        'dashboard.widget.conversations',
        'dashboard.widget.online',
        'dashboard.widget.messages',
        'dashboard.widget.security',
        'security.view'
      )
    `);
    
    console.log('📋 Found permissions:');
    permissions.forEach(p => console.log(`  ✅ ${p.name} (ID: ${p.id})`));
    
    // Add role-permission mappings for Super Admin (role_id = 1)
    for (const perm of permissions) {
      try {
        await connection.execute(
          'INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)',
          [1, perm.id]
        );
        console.log(`✅ Added mapping for ${perm.name}`);
      } catch (error) {
        if (error.code === 'ER_DUP_ENTRY') {
          console.log(`⚠️ Mapping already exists for ${perm.name}`);
        } else {
          console.log(`❌ Error adding ${perm.name}: ${error.message}`);
        }
      }
    }
    
    // Verify mappings
    const [mappings] = await connection.execute(`
      SELECT p.name 
      FROM permissions p
      JOIN role_permissions rp ON p.id = rp.permission_id
      WHERE rp.role_id = 1 AND p.name IN (
        'dashboard.widget.conversations',
        'dashboard.widget.online',
        'dashboard.widget.messages',
        'dashboard.widget.security',
        'security.view'
      )
    `);
    
    console.log('\n🔗 Verified role-permission mappings:');
    mappings.forEach(m => console.log(`  ✅ ${m.name}`));
    
    await connection.end();
  } catch (error) {
    console.error('❌ Error:', error.message);
  }
}

fixRolePermissionMappings();
