/**
 * Test Login with CSRF Token
 */

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

async function testLoginWithCSRF() {
  console.log('🔐 Testing Login Authentication Flow\n');

  try {
    // Step 1: Get CSRF token
    console.log('1️⃣ Getting CSRF token...');
    const csrfResponse = await fetch(`${BASE_URL}/api/csrf`, {
      method: 'GET',
      credentials: 'include',
    });
    const csrfData = await csrfResponse.json();
    const csrfToken = csrfData.csrfToken;
    console.log(`   ✅ CSRF token obtained: ${csrfToken}\n`);

    // Step 2: Test with INVALID credentials (non-existent user)
    console.log('2️⃣ Testing with INVALID user (should fail)...');
    const invalidResponse = await fetch(`${BASE_URL}/api/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify({
        identifier: 'nonexistent@example.com',
        password: 'WrongPassword123!',
        csrfToken: csrfToken,
      }),
    });

    const invalidData = await invalidResponse.json();
    console.log(`   Status: ${invalidResponse.status}`);
    console.log(`   Response: ${JSON.stringify(invalidData, null, 2)}`);

    if (invalidResponse.status === 401 || invalidResponse.status === 403) {
      console.log('   ✅ Invalid user correctly rejected\n');
    } else {
      console.log('   ❌ SECURITY ISSUE: Invalid user was NOT rejected!\n');
    }

    // Step 3: Test with WRONG password for existing user
    console.log('3️⃣ Testing with WRONG password for real user (should fail)...');
    const wrongPasswordResponse = await fetch(`${BASE_URL}/api/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify({
        identifier: 'realtest@mawidi.com', // We saw this user in database
        password: 'WrongPassword123!',
        csrfToken: csrfToken,
      }),
    });

    const wrongPasswordData = await wrongPasswordResponse.json();
    console.log(`   Status: ${wrongPasswordResponse.status}`);
    console.log(`   Response: ${JSON.stringify(wrongPasswordData, null, 2)}`);

    if (wrongPasswordResponse.status === 401) {
      console.log('   ✅ Wrong password correctly rejected\n');
    } else {
      console.log('   ❌ SECURITY ISSUE: Wrong password was NOT rejected!\n');
    }

    // Step 4: Test NextAuth credentials endpoint
    console.log('4️⃣ Testing NextAuth credentials provider...');
    const nextAuthResponse = await fetch(`${BASE_URL}/api/auth/callback/credentials`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      credentials: 'include',
      body: new URLSearchParams({
        email: 'nonexistent@example.com',
        password: 'WrongPassword123!',
        csrfToken: csrfToken,
        callbackUrl: '/en/dashboard',
      }).toString(),
    });

    console.log(`   Status: ${nextAuthResponse.status}`);
    const nextAuthText = await nextAuthResponse.text();
    console.log(`   Response preview: ${nextAuthText.substring(0, 200)}...\n`);

    // Step 5: Test unauthenticated dashboard access
    console.log('5️⃣ Testing dashboard access without authentication...');
    const dashboardResponse = await fetch(`${BASE_URL}/api/dashboard/access`, {
      method: 'GET',
    });

    console.log(`   Status: ${dashboardResponse.status}`);
    const dashboardData = await dashboardResponse.json();
    console.log(`   Response: ${JSON.stringify(dashboardData, null, 2)}`);

    if (dashboardResponse.status === 401) {
      console.log('   ✅ Dashboard correctly protected\n');
    } else {
      console.log('   ❌ SECURITY ISSUE: Dashboard accessible without auth!\n');
    }

    // Step 6: Test if we can bypass by directly accessing dashboard page
    console.log('6️⃣ Testing direct dashboard page access (client-side protection)...');
    const pageResponse = await fetch(`${BASE_URL}/en/dashboard`, {
      method: 'GET',
      redirect: 'manual',
    });

    console.log(`   Status: ${pageResponse.status}`);
    if (pageResponse.status === 302 || pageResponse.status === 307) {
      const location = pageResponse.headers.get('location');
      console.log(`   Redirects to: ${location}`);
      if (location?.includes('/login')) {
        console.log('   ✅ Dashboard page redirects to login\n');
      }
    } else if (pageResponse.status === 200) {
      console.log('   ⚠️  Page loads (client-side protection only)\n');
    }

    console.log('='.repeat(70));
    console.log('🎯 CRITICAL FINDINGS:\n');
    console.log('The authentication system is using:');
    console.log('1. NextAuth for session management');
    console.log('2. Custom login API for email/password validation');
    console.log('3. Client-side redirect to login if not authenticated');
    console.log('\nTo properly test login, you need:');
    console.log('- A valid user email and password');
    console.log('- CSRF token from /api/csrf');
    console.log('- Credentials passed to NextAuth callback endpoint');
    console.log('='.repeat(70));

  } catch (error) {
    console.error('❌ Test error:', error);
  }
}

testLoginWithCSRF();
