/**
 * Reproduce Login Bug - Test with completely fake credentials
 */

async function testFakeLogin() {
  const BASE_URL = 'http://localhost:9000';

  console.log('🧪 REPRODUCING BUG: Testing login with fake credentials\n');
  console.log('Credentials:');
  console.log('  Email: totallyfake@notreal.com');
  console.log('  Password: RandomPassword123!\n');

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

    // Step 2: Try to login with completely fake credentials
    console.log('2️⃣ Attempting login with fake credentials...');
    const loginResponse = await fetch(`${BASE_URL}/api/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify({
        identifier: 'totallyfake@notreal.com',
        password: 'RandomPassword123!',
        csrfToken: csrfData.csrfToken,
      }),
    });

    console.log(`   Status: ${loginResponse.status}`);
    const loginData = await loginResponse.json();
    console.log(`   Response: ${JSON.stringify(loginData, null, 2)}\n`);

    // Step 3: Check if we somehow got a session
    console.log('3️⃣ Checking session after fake login...');
    const sessionResponse = await fetch(`${BASE_URL}/api/auth/session`, {
      credentials: 'include',
    });
    const sessionData = await sessionResponse.json();
    console.log(`   Session: ${JSON.stringify(sessionData, null, 2)}\n`);

    // Step 4: Try to access dashboard
    console.log('4️⃣ Trying to access dashboard...');
    const dashboardResponse = await fetch(`${BASE_URL}/api/dashboard/access`, {
      credentials: 'include',
    });
    console.log(`   Status: ${dashboardResponse.status}`);
    const dashboardData = await dashboardResponse.json();
    console.log(`   Response: ${JSON.stringify(dashboardData, null, 2)}\n`);

    // Step 5: Try NextAuth callback endpoint directly
    console.log('5️⃣ Testing NextAuth callback endpoint...');
    const callbackResponse = await fetch(`${BASE_URL}/api/auth/callback/credentials`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      credentials: 'include',
      body: new URLSearchParams({
        email: 'totallyfake@notreal.com',
        password: 'RandomPassword123!',
        csrfToken: csrfData.csrfToken,
        callbackUrl: '/en/dashboard',
      }).toString(),
    });

    console.log(`   Status: ${callbackResponse.status}`);

    // Check for redirect
    const location = callbackResponse.headers.get('location');
    if (location) {
      console.log(`   Redirects to: ${location}`);
    }

    // Check response body
    const contentType = callbackResponse.headers.get('content-type');
    if (contentType?.includes('html')) {
      const html = await callbackResponse.text();
      if (html.includes('dashboard')) {
        console.log('   ⚠️  Response mentions dashboard!');
      }
      if (html.includes('error')) {
        console.log('   ✅ Response contains error');
      }
    } else {
      const callbackData = await callbackResponse.json();
      console.log(`   Response: ${JSON.stringify(callbackData, null, 2)}`);
    }

    console.log('\n' + '='.repeat(70));
    console.log('🔍 ANALYSIS:');
    console.log('='.repeat(70));

    if (sessionData?.user) {
      console.log('❌ CRITICAL BUG CONFIRMED!');
      console.log('   Fake credentials created a session!');
      console.log('   This is a MAJOR security vulnerability!');
    } else if (dashboardData?.hasAccess) {
      console.log('❌ CRITICAL BUG CONFIRMED!');
      console.log('   Dashboard access granted without session!');
    } else if (loginResponse.status === 200 && loginData.success) {
      console.log('❌ BUG FOUND!');
      console.log('   Login API accepted fake credentials!');
    } else {
      console.log('✅ Authentication appears to be working correctly');
      console.log('   Fake credentials were rejected');
      console.log('   No session was created');
      console.log('   Dashboard access denied');
    }

  } catch (error) {
    console.error('Error during test:', error);
  }
}

testFakeLogin();
