const { pool } = require('./src/config/database');

async function testRolesAPI() {
  console.log('🧪 TESTING ROLES API');
  console.log('===================');
  console.log('');

  try {
    // Test 1: Check all roles in database
    console.log('1. Checking all roles in database...');
    const [roles] = await pool.execute(
      `SELECT id, name, description, level, is_active, created_at, updated_at 
       FROM roles 
       WHERE is_active = 1 
       ORDER BY level DESC, name ASC`
    );

    console.log(`   ✅ Found ${roles.length} active roles:`);
    roles.forEach(role => {
      console.log(`     - ID: ${role.id}, Name: "${role.name}", Level: ${role.level}`);
    });
    console.log('');

    // Test 2: Check roles excluding Super Admin
    console.log('2. Checking roles excluding Super Admin...');
    const filteredRoles = roles.filter(role => 
      role.name !== 'Super Admin' && role.name !== 'Super_admin'
    );

    console.log(`   ✅ Found ${filteredRoles.length} roles (excluding Super Admin):`);
    filteredRoles.forEach(role => {
      console.log(`     - ID: ${role.id}, Name: "${role.name}", Level: ${role.level}`);
    });
    console.log('');

    // Test 3: Check if all expected roles are present
    console.log('3. Verifying expected roles are present...');
    const expectedRoles = ['Admin', 'Manager', 'Officer', 'User', 'Navy_admin'];
    const foundRoles = filteredRoles.map(role => role.name);
    
    expectedRoles.forEach(expectedRole => {
      if (foundRoles.includes(expectedRole)) {
        console.log(`   ✅ ${expectedRole} role found`);
      } else {
        console.log(`   ❌ ${expectedRole} role missing`);
      }
    });
    console.log('');

    // Test 4: Check role permissions
    console.log('4. Checking role permissions...');
    for (const role of filteredRoles) {
      const [permissions] = await pool.execute(
        `SELECT p.name FROM permissions p
         JOIN role_permissions rp ON p.id = rp.permission_id
         WHERE rp.role_id = ?`,
        [role.id]
      );
      
      console.log(`   ${role.name}: ${permissions.length} permissions`);
    }
    console.log('');

    console.log('===================');
    console.log('✅ ROLES API TEST COMPLETE');
    console.log('');
    console.log('📋 SUMMARY:');
    console.log(`   - Total active roles: ${roles.length}`);
    console.log(`   - Roles for dropdown: ${filteredRoles.length}`);
    console.log(`   - Super Admin excluded: ✅`);
    console.log(`   - All expected roles present: ${expectedRoles.every(role => foundRoles.includes(role)) ? '✅' : '❌'}`);

  } catch (error) {
    console.error('❌ Error testing roles API:', error);
  } finally {
    await pool.end();
  }
}

testRolesAPI();
