/**
 * Comprehensive Password Security Test
 * Tests multiple wrong passwords to ensure authentication properly validates
 */

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_PASSWORDS = [
  'WrongPassword123!',
  'incorrect',
  '12345678',
  'password',
  '',
  'eGj&tk!@%T8sFMOq#3QP1', // Almost correct but extra character
  'random@#$%password',
];

async function testPassword(password: string, shouldSucceed: boolean): Promise<boolean> {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext();
  const page = await context.newPage();

  let success = false;

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

    // Fill form
    await page.locator('input[type="text"]').fill(TEST_EMAIL);
    await page.locator('input[type="password"]').fill(password);

    // Submit
    await page.locator('button[type="submit"]').click();

    // Wait and check result
    await page.waitForTimeout(3000);

    const currentUrl = page.url();
    const onDashboard = currentUrl.includes('/dashboard');

    if (onDashboard === shouldSucceed) {
      success = true;
    }

    return success;

  } catch (error) {
    return false;
  } finally {
    await browser.close();
  }
}

async function runSecurityTests() {
  console.log('=== Password Security Validation Tests ===');
  console.log('');

  let allPassed = true;

  // Test 1: Correct password should work
  console.log('Test 1: Correct password should ALLOW login');
  console.log(`Password: ${CORRECT_PASSWORD.substring(0, 4)}...`);
  const test1 = await testPassword(CORRECT_PASSWORD, true);
  if (test1) {
    console.log('✅ PASS - Correct password allows login');
  } else {
    console.log('❌ FAIL - Correct password rejected');
    allPassed = false;
  }
  console.log('');

  // Test 2-8: Wrong passwords should fail
  for (let i = 0; i < WRONG_PASSWORDS.length; i++) {
    const wrongPass = WRONG_PASSWORDS[i];
    console.log(`Test ${i + 2}: Wrong password should DENY login`);
    console.log(`Password: "${wrongPass}"`);

    const testResult = await testPassword(wrongPass, false);

    if (testResult) {
      console.log('✅ PASS - Wrong password rejected');
    } else {
      console.log('❌ FAIL - Wrong password allowed login (SECURITY BUG!)');
      allPassed = false;
    }
    console.log('');
  }

  console.log('=== Security Test Summary ===');
  if (allPassed) {
    console.log('✅✅✅ ALL TESTS PASSED ✅✅✅');
    console.log('✅ Authentication properly validates passwords');
    console.log('✅ System is secure');
  } else {
    console.log('❌❌❌ SECURITY VULNERABILITIES DETECTED ❌❌❌');
    console.log('❌ Authentication validation is BROKEN');
    console.log('❌ IMMEDIATE FIX REQUIRED');
  }
}

runSecurityTests();
