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

async function testSuperAdminLoginResponse() {
  try {
    console.log('🔍 Testing Super Admin Login Response...');
    
    // First, get Super Admin user details from database
    const connection = await mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: '',
      database: 'cms_db'
    });

    const [users] = await connection.execute('SELECT * FROM users WHERE role_id = 1 LIMIT 1');
    if (users.length === 0) {
      console.log('❌ No Super Admin user found');
      return;
    }

    const superAdmin = users[0];
    console.log('✅ Super Admin user found:', {
      id: superAdmin.id,
      name: superAdmin.name,
      email: superAdmin.email,
      role_id: superAdmin.role_id
    });

    // Test login API
    try {
      console.log('\n🔑 Testing Login API...');
      const loginResponse = await axios.post('http://localhost:5000/api/auth/login', {
        email: superAdmin.email,
        password: 'admin123' // Default password
      });

      console.log('✅ Login Response Status:', loginResponse.status);
      
      if (loginResponse.data && loginResponse.data.data) {
        const userData = loginResponse.data.data.user;
        console.log('\n👤 User Data from API:');
        console.log(`  ID: ${userData.id}`);
        console.log(`  Name: ${userData.name}`);
        console.log(`  Email: ${userData.email}`);
        console.log(`  Role: "${userData.role}"`);
        console.log(`  Role ID: ${userData.role_id}`);
        console.log(`  Permissions Count: ${userData.permissions?.length || 0}`);
        
        console.log('\n📋 First 10 Permissions:');
        userData.permissions?.slice(0, 10).forEach(perm => {
          console.log(`  ✅ ${perm}`);
        });
        
        if (userData.permissions?.length > 10) {
          console.log(`  ... and ${userData.permissions.length - 10} more permissions`);
        }

        // Check critical permissions
        const criticalPerms = [
          'dashboard.view',
          'settings.access',
          'admin.access',
          'user.read'
        ];
        
        console.log('\n🎯 Critical Permissions Check:');
        criticalPerms.forEach(perm => {
          const hasPermission = userData.permissions?.includes(perm);
          console.log(`  ${hasPermission ? '✅' : '❌'} ${perm}`);
        });

        // Check if role matches expected format
        console.log('\n🔍 Role Format Check:');
        console.log(`  Expected: "Super Admin"`);
        console.log(`  Actual: "${userData.role}"`);
        console.log(`  Match: ${userData.role === 'Super Admin' ? '✅ YES' : '❌ NO'}`);

      } else {
        console.log('❌ No user data in response');
      }

    } catch (apiError) {
      console.log('❌ API Error:', apiError.response?.data?.message || apiError.message);
      if (apiError.response?.status === 500) {
        console.log('💡 Backend server might not be running. Please start it with: npm run dev');
      }
    }

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

testSuperAdminLoginResponse();
