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

// Database configuration
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'cms_db',
  port: 3306
};

async function fixRole16DashboardPermissions() {
  let connection;
  
  try {
    console.log('🔧 Fixing Role ID 16 Dashboard Widget Permissions...\n');
    
    connection = await mysql.createConnection(dbConfig);
    
    // Dashboard widget permissions to add to role_id 16
    const dashboardWidgetPermissions = [
      'dashboard.widget.total_contacts',
      'dashboard.widget.active_conversations', 
      'dashboard.widget.online_contacts',
      'dashboard.widget.user_management'
    ];
    
    console.log('📋 Adding Dashboard Widget Permissions to Role ID 16:');
    
    // Get permission IDs
    const [permissions] = await connection.execute(`
      SELECT id, name FROM permissions 
      WHERE name IN (?, ?, ?, ?)
    `, dashboardWidgetPermissions);
    
    console.log(`   Found ${permissions.length} permissions:`);
    permissions.forEach(perm => {
      console.log(`   - ${perm.name} (ID: ${perm.id})`);
    });
    
    // Assign permissions to role_id 16
    console.log('\n🔗 Assigning Permissions to Role ID 16:');
    
    for (const perm of permissions) {
      // Check if already assigned to role_id 16
      const [existing] = await connection.execute(`
        SELECT id FROM role_permissions 
        WHERE role_id = 16 AND permission_id = ?
      `, [perm.id]);
      
      if (existing.length > 0) {
        console.log(`      ⚠️  Role ID 16 already has '${perm.name}'`);
      } else {
        // Assign permission to role_id 16
        await connection.execute(`
          INSERT INTO role_permissions (role_id, permission_id)
          VALUES (16, ?)
        `, [perm.id]);
        
        console.log(`      ✅ Assigned '${perm.name}' to Role ID 16`);
      }
    }
    
    // Verify assignments for role_id 16
    console.log('\n🔍 Verifying Dashboard Widget Permissions for Role ID 16:');
    const [verification] = 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 = 16 
      AND p.name IN ('dashboard.widget.total_contacts', 'dashboard.widget.active_conversations', 'dashboard.widget.online_contacts', 'dashboard.widget.user_management')
      ORDER BY p.name
    `);
    
    console.log(`   Role ID 16 now has ${verification.length} dashboard widget permissions:`);
    verification.forEach(perm => {
      console.log(`      ✅ ${perm.name}: ${perm.description}`);
    });
    
    // Final verification
    if (verification.length === 4) {
      console.log('\n🎉 SUCCESS: Role ID 16 now has all 4 dashboard widget permissions!');
      console.log('   ✅ Total Contacts widget');
      console.log('   ✅ Active Conversations widget');
      console.log('   ✅ Online Contacts widget');
      console.log('   ✅ User Management widget');
    } else {
      console.log(`\n⚠️  Role ID 16 has ${verification.length}/4 dashboard widget permissions`);
    }
    
  } catch (error) {
    console.error('❌ Error:', error.message);
  } finally {
    if (connection) {
      await connection.end();
    }
  }
}

fixRole16DashboardPermissions();
