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

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

    // Get Super Admin user
    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 {
      const loginResponse = await axios.post('http://localhost:5000/api/auth/login', {
        email: superAdmin.email,
        password: 'admin123' // Default password
      });

      console.log('\n🔑 Login Response:');
      console.log('Status:', loginResponse.status);
      console.log('Token:', loginResponse.data.token ? 'Present' : 'Missing');
      
      if (loginResponse.data.user) {
        console.log('User Data:', {
          id: loginResponse.data.user.id,
          name: loginResponse.data.user.name,
          role: loginResponse.data.user.role,
          permissions: loginResponse.data.user.permissions?.length || 0
        });
        
        console.log('\n📋 User Permissions:');
        loginResponse.data.user.permissions?.forEach(perm => {
          console.log(`  ✅ ${perm}`);
        });
      }

      // Test profile API
      const profileResponse = await axios.get('http://localhost:5000/api/auth/profile', {
        headers: {
          'Authorization': `Bearer ${loginResponse.data.token}`
        }
      });

      console.log('\n👤 Profile Response:');
      console.log('Status:', profileResponse.status);
      if (profileResponse.data.user) {
        console.log('Profile User Data:', {
          id: profileResponse.data.user.id,
          name: profileResponse.data.user.name,
          role: profileResponse.data.user.role,
          permissions: profileResponse.data.user.permissions?.length || 0
        });
      }

    } catch (apiError) {
      console.log('❌ API Error:', apiError.response?.data?.message || apiError.message);
    }

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

testSuperAdminLogin();
