import { test, expect } from '@playwright/test';
import { testConfig } from '../../utils/test-config';
import { printTestCase, printSuccess, printWarning } from '../../helpers/test-helpers';

/**
 * Invalid Login Test
 * Tags: @auth @p2 @security
 * 
 * Tests login with invalid credentials and security measures
 */

test.describe('01_Authentication - Invalid Login @auth @p2 @security', () => {
  
  test('Test Case 1: Empty credentials', async ({ page }) => {
    printTestCase(1, 'Empty Credentials');
    
    await page.goto('/');
    await page.waitForTimeout(2000);
    
    // Try to submit with empty fields
    const loginButton = page.locator('button:has-text("LOGIN"), button:has-text("Login"), input[type="submit"]').first();
    await loginButton.click();
    await page.waitForTimeout(2000);
    
    // Should still be on login page
    const currentUrl = page.url();
    expect(currentUrl.includes('/login') || currentUrl === testConfig.baseUrl + '/').toBeTruthy();
    printSuccess('Empty login rejected - still on login page');
    
    // Check for validation error
    const emailField = page.locator('input[type="email"], input[placeholder*="email" i]').first();
    const hasRequiredAttr = await emailField.evaluate(el => el.hasAttribute('required'));
    if (hasRequiredAttr) {
      printSuccess('Email field has required attribute');
    }
  });
  
  test('Test Case 2: Invalid email format', async ({ page }) => {
    printTestCase(2, 'Invalid Email Format');
    
    await page.goto('/');
    await page.waitForTimeout(2000);
    
    const emailField = page.locator('input[type="email"], input[placeholder*="email" i]').first();
    const passwordField = page.locator('input[type="password"]').first();
    const loginButton = page.locator('button:has-text("LOGIN"), button:has-text("Login")').first();
    
    // Try invalid email format
    await emailField.fill('notanemail');
    await passwordField.fill('somepassword');
    await loginButton.click();
    await page.waitForTimeout(2000);
    
    // Should be rejected (either client-side validation or server-side)
    printSuccess('Invalid email format handled');
  });
  
  test('Test Case 3: Wrong password', async ({ page }) => {
    printTestCase(3, 'Wrong Password');
    
    await page.goto('/');
    await page.waitForTimeout(2000);
    
    const emailField = page.locator('input[type="email"], input[placeholder*="email" i]').first();
    const passwordField = page.locator('input[type="password"]').first();
    const loginButton = page.locator('button:has-text("LOGIN"), button:has-text("Login")').first();
    
    // Try valid email but wrong password
    await emailField.fill(testConfig.testEmail);
    await passwordField.fill('WrongPassword123!');
    await loginButton.click();
    await page.waitForTimeout(3000);
    
    // Should still be on login page
    const currentUrl = page.url();
    expect(currentUrl.includes('/login') || currentUrl === testConfig.baseUrl + '/').toBeTruthy();
    printSuccess('Wrong password rejected');
    
    // Look for error message
    const errorSelectors = [
      '.error',
      '.alert-danger',
      '.text-danger',
      '[class*="error"]',
      ':text("Invalid")',
      ':text("incorrect")',
      ':text("wrong")'
    ];
    
    for (const selector of errorSelectors) {
      const errorMsg = page.locator(selector);
      const hasError = await errorMsg.isVisible({ timeout: 2000 }).catch(() => false);
      if (hasError) {
        const errorText = await errorMsg.textContent();
        printSuccess(`Error message displayed: ${errorText?.substring(0, 50)}`);
        break;
      }
    }
  });
  
  test('Test Case 4: Non-existent user', async ({ page }) => {
    printTestCase(4, 'Non-existent User');
    
    await page.goto('/');
    await page.waitForTimeout(2000);
    
    const emailField = page.locator('input[type="email"], input[placeholder*="email" i]').first();
    const passwordField = page.locator('input[type="password"]').first();
    const loginButton = page.locator('button:has-text("LOGIN"), button:has-text("Login")').first();
    
    // Try non-existent email
    await emailField.fill('nonexistent@example.com');
    await passwordField.fill('SomePassword123!');
    await loginButton.click();
    await page.waitForTimeout(3000);
    
    // Should still be on login page
    const currentUrl = page.url();
    expect(currentUrl.includes('/login') || currentUrl === testConfig.baseUrl + '/').toBeTruthy();
    printSuccess('Non-existent user rejected');
  });
  
  test('Test Case 5: SQL injection attempt', async ({ page }) => {
    printTestCase(5, 'SQL Injection Attempt');
    
    await page.goto('/');
    await page.waitForTimeout(2000);
    
    const emailField = page.locator('input[type="email"], input[placeholder*="email" i]').first();
    const passwordField = page.locator('input[type="password"]').first();
    const loginButton = page.locator('button:has-text("LOGIN"), button:has-text("Login")').first();
    
    // Try SQL injection patterns
    const injectionPatterns = [
      "admin' OR '1'='1",
      "admin'--",
      "' OR '1'='1' --",
      "'; DROP TABLE users--"
    ];
    
    for (const pattern of injectionPatterns) {
      await emailField.fill(pattern);
      await passwordField.fill('password');
      await loginButton.click();
      await page.waitForTimeout(2000);
      
      // Should be rejected
      const currentUrl = page.url();
      expect(currentUrl.includes('/login') || currentUrl === testConfig.baseUrl + '/').toBeTruthy();
    }
    
    printSuccess('SQL injection attempts properly rejected');
  });
  
  test('Test Case 6: XSS attempt', async ({ page }) => {
    printTestCase(6, 'XSS Attempt');
    
    await page.goto('/');
    await page.waitForTimeout(2000);
    
    const emailField = page.locator('input[type="email"], input[placeholder*="email" i]').first();
    const passwordField = page.locator('input[type="password"]').first();
    const loginButton = page.locator('button:has-text("LOGIN"), button:has-text("Login")').first();
    
    // Try XSS patterns
    const xssPattern = '<script>alert("XSS")</script>';
    
    await emailField.fill(xssPattern);
    await passwordField.fill('password');
    await loginButton.click();
    await page.waitForTimeout(2000);
    
    // Check that script did not execute
    const dialogPromise = page.waitForEvent('dialog', { timeout: 1000 }).catch(() => null);
    const dialog = await dialogPromise;
    
    if (dialog) {
      await dialog.dismiss();
      printWarning('XSS script executed - SECURITY ISSUE');
      expect(dialog).toBeNull(); // This will fail, indicating a security problem
    } else {
      printSuccess('XSS attempt properly sanitized');
    }
  });
  
  test('Test Case 7: Very long input', async ({ page }) => {
    printTestCase(7, 'Very Long Input');
    
    await page.goto('/');
    await page.waitForTimeout(2000);
    
    const emailField = page.locator('input[type="email"], input[placeholder*="email" i]').first();
    const passwordField = page.locator('input[type="password"]').first();
    const loginButton = page.locator('button:has-text("LOGIN"), button:has-text("Login")').first();
    
    // Try very long input (buffer overflow attempt)
    const longString = 'a'.repeat(10000);
    
    await emailField.fill(longString);
    await passwordField.fill(longString);
    await loginButton.click();
    await page.waitForTimeout(2000);
    
    // Should handle gracefully
    const currentUrl = page.url();
    expect(currentUrl.includes('/login') || currentUrl === testConfig.baseUrl + '/').toBeTruthy();
    printSuccess('Very long input handled gracefully');
  });
  
  test('Test Case 8: Special characters', async ({ page }) => {
    printTestCase(8, 'Special Characters');
    
    await page.goto('/');
    await page.waitForTimeout(2000);
    
    const emailField = page.locator('input[type="email"], input[placeholder*="email" i]').first();
    const passwordField = page.locator('input[type="password"]').first();
    const loginButton = page.locator('button:has-text("LOGIN"), button:has-text("Login")').first();
    
    // Try special characters
    await emailField.fill('test@example.com');
    await passwordField.fill('!@#$%^&*()_+-=[]{}|;:,.<>?');
    await loginButton.click();
    await page.waitForTimeout(2000);
    
    // Should handle special characters
    printSuccess('Special characters handled');
  });
});

