/**
 * Visual Authentication Test
 * Opens browser and tests authentication with screenshots
 */

import { chromium } from '@playwright/test';

const BASE_URL = 'http://localhost:9000';
const TEST_EMAIL = 'gara2222ge@support.com';
const CORRECT_PASSWORD = 'eGj&tk!@%T8sFMOq#3QP';
const WRONG_PASSWORD = 'DefinitelyWrongPassword123!';

async function visualAuthTest() {
  console.log('=== Visual Authentication Demonstration ===');
  console.log('');

  const browser = await chromium.launch({
    headless: false,
    slowMo: 1000 // Slow down actions for visual clarity
  });
  const context = await browser.newContext();
  const page = await context.newPage();

  try {
    // TEST 1: Wrong Password Should Fail
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('TEST 1: Login with WRONG Password');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`Email: ${TEST_EMAIL}`);
    console.log(`Password: ${WRONG_PASSWORD}`);
    console.log('Expected Result: LOGIN SHOULD FAIL');
    console.log('');

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

    await page.locator('input[type="text"]').fill(TEST_EMAIL);
    console.log('✅ Entered email');

    await page.locator('input[type="password"]').fill(WRONG_PASSWORD);
    console.log('✅ Entered WRONG password');

    await page.locator('button[type="submit"]').click();
    console.log('✅ Clicked submit');

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

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

    await page.screenshot({ path: 'auth-test-1-wrong-password.png', fullPage: true });

    if (url1.includes('/dashboard')) {
      console.log('');
      console.log('🚨 SECURITY BUG: Wrong password allowed login!');
      console.log('');
    } else {
      console.log('');
      console.log('✅ CORRECT: Wrong password rejected');
      const errorVisible = await page.locator('[class*="red"]').isVisible().catch(() => false);
      if (errorVisible) {
        const errorText = await page.locator('[class*="red"]').first().textContent();
        console.log(`✅ Error shown: "${errorText}"`);
      }
      console.log('Screenshot: auth-test-1-wrong-password.png');
      console.log('');
    }

    // Clear error and prepare for next test
    await page.waitForTimeout(2000);

    // TEST 2: Correct Password Should Succeed
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('TEST 2: Login with CORRECT Password');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`Email: ${TEST_EMAIL}`);
    console.log(`Password: ${CORRECT_PASSWORD.substring(0, 6)}...`);
    console.log('Expected Result: LOGIN SHOULD SUCCEED');
    console.log('');

    // Reload to clear form
    await page.goto(`${BASE_URL}/en/login`, { waitUntil: 'networkidle' });
    console.log('✅ Reloaded login page');

    await page.locator('input[type="text"]').fill(TEST_EMAIL);
    console.log('✅ Entered email');

    await page.locator('input[type="password"]').fill(CORRECT_PASSWORD);
    console.log('✅ Entered CORRECT password');

    await page.locator('button[type="submit"]').click();
    console.log('✅ Clicked submit');

    // Wait for navigation
    try {
      await page.waitForURL('**/dashboard', { timeout: 15000 });
      console.log('✅ Navigated to dashboard');
    } catch (e) {
      console.log('⚠️ Navigation timeout');
    }

    await page.waitForTimeout(2000);

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

    await page.screenshot({ path: 'auth-test-2-correct-password.png', fullPage: true });

    if (url2.includes('/dashboard')) {
      console.log('');
      console.log('✅ CORRECT: Valid password allowed login');
      console.log('✅ Successfully accessed dashboard');
      console.log('Screenshot: auth-test-2-correct-password.png');
      console.log('');
    } else {
      console.log('');
      console.log('❌ BUG: Correct password rejected!');
      console.log('');
    }

    // Summary
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('TEST SUMMARY');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');

    const test1Pass = !url1.includes('/dashboard');
    const test2Pass = url2.includes('/dashboard');

    console.log(`Test 1 (Wrong Password): ${test1Pass ? '✅ PASS' : '❌ FAIL'}`);
    console.log(`Test 2 (Correct Password): ${test2Pass ? '✅ PASS' : '❌ FAIL'}`);
    console.log('');

    if (test1Pass && test2Pass) {
      console.log('✅✅✅ AUTHENTICATION IS SECURE ✅✅✅');
      console.log('✅ Only correct passwords allow login');
      console.log('✅ Wrong passwords are properly rejected');
    } else {
      console.log('🚨🚨🚨 SECURITY ISSUES DETECTED 🚨🚨🚨');
    }

    console.log('');
    console.log('Screenshots saved:');
    console.log('- auth-test-1-wrong-password.png');
    console.log('- auth-test-2-correct-password.png');

    await page.waitForTimeout(3000);

  } catch (error) {
    console.error('❌ Test error:', error);
  } finally {
    await browser.close();
  }
}

visualAuthTest();
