const axios = require('axios');

const API_URL = 'http://localhost:4000';

async function testLogin() {
  console.log('🧪 Testing Backend Login Endpoint\n');
  console.log('API URL:', API_URL);
  console.log('Endpoint:', `${API_URL}/auth/login`);
  console.log('Credentials: admin@edr-platform.com / admin123\n');

  try {
    const response = await axios.post(`${API_URL}/auth/login`, {
      email: 'admin@edr-platform.com',
      password: 'admin123'
    });

    console.log('✅ Login Successful!\n');
    console.log('Status:', response.status);
    console.log('Response Data:', JSON.stringify(response.data, null, 2));
    
    if (response.data.token && response.data.user) {
      console.log('\n✅ Response structure is correct');
      console.log('Token:', response.data.token.substring(0, 50) + '...');
      console.log('User ID:', response.data.user.id);
      console.log('User Email:', response.data.user.email);
      console.log('User Role:', response.data.user.role);
    } else {
      console.log('\n❌ Response structure is incorrect');
      console.log('Expected: { token, user }');
      console.log('Got:', Object.keys(response.data));
    }

  } catch (error) {
    console.log('❌ Login Failed!\n');
    
    if (error.code === 'ECONNREFUSED') {
      console.log('Error: Cannot connect to backend');
      console.log('Solution: Start backend with: pnpm --filter @edr/passenger-api run dev');
    } else if (error.response) {
      console.log('Status:', error.response.status);
      console.log('Error Data:', JSON.stringify(error.response.data, null, 2));
      
      if (error.response.status === 401) {
        console.log('\nPossible causes:');
        console.log('1. Database not seeded - Run: pnpm --filter @edr/passenger-api run prisma:seed');
        console.log('2. Wrong credentials');
      }
    } else {
      console.log('Error:', error.message);
    }
  }
}

testLogin();
