/**
 * Security Test - Wrong Password Should Fail
 * Tests that authentication properly rejects incorrect passwords
 */

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

const BASE_URL = 'http://localhost:9000';
const TEST_EMAIL = 'gara2222ge@support.com';
const WRONG_PASSWORD = 'WrongPassword123!'; // Intentionally wrong

async function testWrongPassword() {
  console.log('=== Security Test: Wrong Password Should Be Rejected ===');
  console.log(`Testing with: ${TEST_EMAIL}`);
  console.log(`Using WRONG password: ${WRONG_PASSWORD}`);
  console.log('');

  const browser = await chromium.launch({ headless: false });
  const context = await browser.newContext();
  const page = await context.newPage();

  try {
    // Enable console logging
    page.on('console', msg => console.log(`[Browser] ${msg.text()}`));

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

    // Fill credentials with WRONG password
    console.log('2. Filling in email and WRONG password...');
    await page.locator('input[type="text"]').fill(TEST_EMAIL);
    await page.locator('input[type="password"]').fill(WRONG_PASSWORD);
    console.log('✅ Credentials filled (with wrong password)');

    // Click submit
    console.log('3. Clicking login button...');
    await page.locator('button[type="submit"]').click();

    // Wait for response
    console.log('4. Waiting for authentication response...');
    await page.waitForTimeout(5000);

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

    // Take screenshot
    await page.screenshot({ path: 'wrong-password-test.png', fullPage: true });
    console.log('Screenshot saved: wrong-password-test.png');

    // Check if we're on dashboard (SHOULD NOT BE!)
    if (currentUrl.includes('/dashboard')) {
      console.log('');
      console.log('🚨🚨🚨 CRITICAL SECURITY BUG! 🚨🚨🚨');
      console.log('❌ User logged in with WRONG password!');
      console.log('❌ Authentication validation is BROKEN!');
      console.log('');
      console.log('This means:');
      console.log('- Password validation is not working');
      console.log('- ANY password allows login');
      console.log('- IMMEDIATE FIX REQUIRED');
      console.log('');

      await page.waitForTimeout(5000); // Keep browser open
    } else {
      // Check for error message
      const errorElement = await page.locator('[class*="red"]').first();
      const hasError = await errorElement.isVisible().catch(() => false);

      if (hasError) {
        const errorText = await errorElement.textContent();
        console.log('');
        console.log('✅✅✅ CORRECT BEHAVIOR ✅✅✅');
        console.log(`✅ Login rejected with error: "${errorText}"`);
        console.log('✅ Password validation is working correctly');
        console.log('');
      } else {
        console.log('');
        console.log('⚠️ No error message shown, but also not on dashboard');
        console.log('⚠️ Check if validation is working');
        console.log('');
        await page.waitForTimeout(3000);
      }
    }

  } catch (error) {
    console.error('❌ Test error:', error);
    await page.screenshot({ path: 'wrong-password-error.png', fullPage: true });
  } finally {
    await browser.close();
  }
}

testWrongPassword();
