const BASE_URL = 'http://localhost:9000';

async function testLoginAPI() {
  try {
    // Step 1: Get CSRF token
    console.log('📡 Step 1: Fetching CSRF token...');
    const csrfResponse = await fetch(`${BASE_URL}/api/auth/csrf`);
    const csrfData = await csrfResponse.json();
    const csrfToken = csrfData.csrfToken;
    const cookies = csrfResponse.headers.get('set-cookie');

    console.log('✅ CSRF Token received:', csrfToken.substring(0, 16) + '...');
    console.log('✅ Cookies:', cookies);

    // Step 2: Attempt login
    console.log('\n📡 Step 2: Attempting login...');
    const loginResponse = await fetch(`${BASE_URL}/api/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': csrfToken,
        'Cookie': cookies,
      },
      body: JSON.stringify({
        identifier: 'logintest0@example.com',
        password: 'Mw!d1T3st#P@ssw0rd2024',
        type: 'email',
      }),
    });

    const loginData = await loginResponse.json();
    console.log('\n📊 Login Response Status:', loginResponse.status);
    console.log('📊 Login Response:', JSON.stringify(loginData, null, 2));

    if (loginResponse.ok) {
      console.log('\n✅ LOGIN SUCCESSFUL!');
      console.log('✅ User:', loginData.user);
      console.log('✅ Token:', loginData.token ? 'Present' : 'Missing');
    } else {
      console.log('\n❌ LOGIN FAILED!');
      console.log('❌ Error:', loginData.error);
    }
  } catch (error) {
    console.error('\n❌ Test failed:', error.message);
  }
}

testLoginAPI();
