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

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

    console.log('🔍 Debugging User Permissions for Dashboard...');
    
    // Check current user details
    const [users] = await connection.execute(`
      SELECT u.id, u.name, u.role_id, r.name as role_name
      FROM users u
      LEFT JOIN roles r ON u.role_id = r.id
      WHERE u.name LIKE '%Nave%'
    `);
    
    console.log('\n👤 Current User Details:');
    users.forEach(user => {
      console.log(`ID: ${user.id}, Name: ${user.name}, Role ID: ${user.role_id}, Role: ${user.role_name}`);
    });

    if (users.length > 0) {
      const currentUser = users[0];
      
      // Get user permissions
      const [permissions] = await connection.execute(`
        SELECT DISTINCT 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
      `, [currentUser.role_id]);
      
      console.log(`\n🎯 Permissions for ${currentUser.name} (Role: ${currentUser.role_name}):`);
      permissions.forEach(perm => {
        console.log(`  ✅ ${perm.name} - ${perm.description}`);
      });

      // Check specific permissions for User Statistics
      const userStatsPermissions = [
        'user.manage_roles',
        'user.read',
        'admin.access',
        'dashboard.analytics',
        'dashboard.view',
        'dashboard.chart'
      ];

      console.log('\n🔍 Checking User Statistics Related Permissions:');
      userStatsPermissions.forEach(permName => {
        const hasPermission = permissions.some(p => p.name === permName);
        console.log(`  ${hasPermission ? '✅' : '❌'} ${permName}`);
      });

      // Check if user is Super Admin or Admin
      console.log('\n👑 Role Check:');
      console.log(`  Role ID: ${currentUser.role_id}`);
      console.log(`  Role Name: ${currentUser.role_name}`);
      console.log(`  Is Super Admin: ${currentUser.role_name === 'Super Admin'}`);
      console.log(`  Is Admin: ${currentUser.role_name === 'Admin'}`);
      
      // Check dashboard stats data
      console.log('\n📊 Dashboard Stats Check:');
      const [stats] = await connection.execute(`
        SELECT COUNT(*) as total_users FROM users
      `);
      console.log(`  Total Users in Database: ${stats[0].total_users}`);
    }

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

debugUserPermissions();
