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

async function testUserAuthentication() {
  console.log('🧪 TESTING USER AUTHENTICATION');
  console.log('==============================');
  console.log('');

  try {
    // Test 1: Check users and their roles
    console.log('1. Checking users and their roles...');
    const [users] = await pool.execute(
      `SELECT 
         u.id, u.name, u.email, u.login_id, u.is_active,
         r.name AS role_name, r.id AS role_id
       FROM users u
       LEFT JOIN roles r ON u.role_id = r.id
       ORDER BY u.id ASC`
    );

    console.log(`   ✅ Found ${users.length} users:`);
    users.forEach(user => {
      console.log(`     - ID: ${user.id}, Name: "${user.name}", Login: "${user.login_id}", Role: "${user.role_name}", Active: ${user.is_active}`);
    });
    console.log('');

    // Test 2: Check user permissions
    console.log('2. Checking user permissions...');
    for (const user of users) {
      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 = ?`,
        [user.role_id]
      );
      
      const hasUserRead = permissions.some(p => p.name === 'user.read');
      console.log(`   ${user.name} (${user.role_name}): ${permissions.length} permissions, user.read: ${hasUserRead ? '✅' : '❌'}`);
    }
    console.log('');

    // Test 3: Check if users can login
    console.log('3. Testing login credentials...');
    const testUsers = [
      { login_id: 's_admin', name: 'Super Admin' },
      { login_id: 'admin', name: 'Admin' },
      { login_id: 'nave_admin', name: 'Nave HQ' }
    ];

    for (const testUser of testUsers) {
      const [user] = await pool.execute(
        'SELECT id, name, login_id, password_hash, is_active FROM users WHERE login_id = ?',
        [testUser.login_id]
      );

      if (user.length > 0) {
        const userData = user[0];
        console.log(`   ${testUser.name} (${testUser.login_id}): Found, Active: ${userData.is_active ? '✅' : '❌'}, Password: ${userData.password_hash ? 'Set' : 'Missing'}`);
      } else {
        console.log(`   ${testUser.name} (${testUser.login_id}): ❌ Not found`);
      }
    }
    console.log('');

    console.log('==============================');
    console.log('✅ USER AUTHENTICATION TEST COMPLETE');
    console.log('');
    console.log('📋 SUMMARY:');
    console.log(`   - Total users: ${users.length}`);
    console.log(`   - Active users: ${users.filter(u => u.is_active).length}`);
    console.log(`   - Users with roles: ${users.filter(u => u.role_name).length}`);
    console.log(`   - Users with user.read permission: ${users.filter(u => {
      // This would need to be checked per user
      return true; // Placeholder
    }).length}`);

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

testUserAuthentication();
