/**
 * Browser Login Test - Simulates User Experience
 *
 * This test simulates exactly what a user does in incognito mode
 */

import { test, expect } from '@playwright/test';

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

test.describe('Browser Login Security Test', () => {
  test('Cannot login with fake credentials and access dashboard', async ({ browser }) => {
    // Create a fresh context (like incognito mode)
    const context = await browser.newContext({
      storageState: undefined, // No cookies, no storage
    });
    const page = await context.newPage();

    console.log('\n🧪 TEST: Login with completely fake credentials\n');

    // Step 1: Go to login page
    console.log('1️⃣ Opening login page...');
    await page.goto(`${BASE_URL}/en/login`, { waitUntil: 'networkidle' });
    console.log('   ✅ Login page loaded\n');

    // Step 2: Enter FAKE credentials
    const fakeEmail = 'totallyfake' + Date.now() + '@notindb.com';
    const fakePassword = 'FakePassword123!';

    console.log('2️⃣ Entering fake credentials:');
    console.log(`   Email: ${fakeEmail}`);
    console.log(`   Password: ${fakePassword}\n`);

    await page.getByPlaceholder(/email/i).first().fill(fakeEmail);
    await page.getByPlaceholder(/password/i).fill(fakePassword);

    // Take screenshot before login
    await page.screenshot({ path: 'test-results/before-fake-login.png' });

    // Step 3: Click login button
    console.log('3️⃣ Clicking login button...');
    await page.getByRole('button', { name: /login|sign in/i }).first().click();

    // Wait for response
    await page.waitForTimeout(3000);

    // Take screenshot after login attempt
    await page.screenshot({ path: 'test-results/after-fake-login.png' });

    // Step 4: Check current URL
    const currentUrl = page.url();
    console.log(`   Current URL: ${currentUrl}\n`);

    // Step 5: Check for error message
    const errorMessage = await page.getByText(/invalid|failed|incorrect|credentials|error/i).first().textContent().catch(() => null);
    console.log(`4️⃣ Error message: ${errorMessage || 'NONE - THIS IS A BUG!'}\n`);

    // Step 6: Check if on dashboard
    const isDashboard = currentUrl.includes('/dashboard');
    console.log(`5️⃣ On dashboard page: ${isDashboard ? '❌ YES - BUG!' : '✅ NO - Good'}\n`);

    // Step 7: Check for session
    const sessionData = await page.evaluate(async () => {
      const response = await fetch('/api/auth/session');
      return await response.json();
    });
    console.log(`6️⃣ Session exists: ${sessionData?.user ? '❌ YES - BUG!' : '✅ NO - Good'}\n`);

    // Step 8: Try to access dashboard directly
    console.log('7️⃣ Trying to access dashboard directly...');
    await page.goto(`${BASE_URL}/en/dashboard`, { waitUntil: 'networkidle' });
    await page.waitForTimeout(2000);

    const finalUrl = page.url();
    console.log(`   Final URL: ${finalUrl}\n`);

    // Take screenshot of dashboard attempt
    await page.screenshot({ path: 'test-results/dashboard-access-attempt.png' });

    console.log('='.repeat(70));
    console.log('📊 TEST RESULTS:\n');

    // Assertions
    if (isDashboard) {
      console.log('❌ CRITICAL BUG: Fake credentials allowed dashboard access!');
      expect(isDashboard).toBe(false);
    } else {
      console.log('✅ PASS: Fake credentials rejected');
    }

    if (sessionData?.user) {
      console.log('❌ CRITICAL BUG: Session created for fake user!');
      expect(sessionData.user).toBeFalsy();
    } else {
      console.log('✅ PASS: No session created');
    }

    if (!finalUrl.includes('/login')) {
      console.log('❌ CRITICAL BUG: Dashboard accessible without login!');
      expect(finalUrl).toContain('/login');
    } else {
      console.log('✅ PASS: Dashboard redirects to login');
    }

    if (!errorMessage) {
      console.log('⚠️  WARNING: No error message shown to user');
    } else {
      console.log(`✅ PASS: Error shown: "${errorMessage}"`);
    }

    console.log('='.repeat(70));

    await context.close();
  });

  test('Can login with valid database credentials', async ({ browser }) => {
    const context = await browser.newContext({
      storageState: undefined,
    });
    const page = await context.newPage();

    console.log('\n🧪 TEST: Login with VALID credentials from database\n');

    await page.goto(`${BASE_URL}/en/login`, { waitUntil: 'networkidle' });

    // Use a known user from database
    // NOTE: You need to know the password for this to work
    const validEmail = 'realtest@mawidi.com';
    const validPassword = 'RealPassword123!'; // User needs to provide this

    console.log('Testing with:');
    console.log(`   Email: ${validEmail}`);
    console.log(`   Password: ${validPassword}\n`);

    await page.getByPlaceholder(/email/i).first().fill(validEmail);
    await page.getByPlaceholder(/password/i).fill(validPassword);

    console.log('Clicking login...');
    await page.getByRole('button', { name: /login|sign in/i }).first().click();

    // Wait for navigation or error
    await page.waitForTimeout(5000);

    const currentUrl = page.url();
    console.log(`Current URL: ${currentUrl}\n`);

    // Take screenshot
    await page.screenshot({ path: 'test-results/valid-login-result.png' });

    if (currentUrl.includes('/dashboard')) {
      console.log('✅ SUCCESS: Valid credentials granted dashboard access');
    } else if (currentUrl.includes('/login')) {
      const errorMsg = await page.getByText(/invalid|failed|incorrect/i).first().textContent().catch(() => null);
      console.log(`❌ FAILED: Valid credentials rejected`);
      console.log(`   Error: ${errorMsg}`);
      console.log(`   Note: Password might be incorrect for ${validEmail}`);
    }

    await context.close();
  });
});
