/**
 * Debug Staff Login Issue
 * Investigates why staff login might not be working
 */

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

const BASE_URL = 'http://localhost:9000';
const STAFF_USERNAME = 'asim';
const STAFF_PASSWORD = 'AsimMawidi2025!';

test.describe('Staff Login - Debug Investigation', () => {
  test('should investigate login flow step by step', async ({ page }) => {
    // Capture all console messages
    const consoleLogs: string[] = [];
    const consoleErrors: string[] = [];

    page.on('console', msg => {
      if (msg.type() === 'error') {
        consoleErrors.push(msg.text());
      } else {
        consoleLogs.push(`[${msg.type()}] ${msg.text()}`);
      }
    });

    // Capture network requests
    const failedRequests: any[] = [];
    page.on('requestfailed', request => {
      failedRequests.push({
        url: request.url(),
        method: request.method(),
        failure: request.failure()?.errorText,
      });
    });

    // Step 1: Navigate to login page
    console.log('Step 1: Navigating to staff login...');
    await page.goto(`${BASE_URL}/staff/login`);
    await page.waitForLoadState('networkidle');

    // Verify login page loaded
    await expect(page).toHaveTitle(/Mawidi Staff/);
    console.log('✓ Login page loaded');

    // Step 2: Fill credentials
    console.log('Step 2: Filling credentials...');
    const usernameInput = page.getByRole('textbox', { name: /username/i });
    const passwordInput = page.getByRole('textbox', { name: /password/i });

    await expect(usernameInput).toBeVisible();
    await expect(passwordInput).toBeVisible();

    await usernameInput.fill(STAFF_USERNAME);
    await passwordInput.fill(STAFF_PASSWORD);
    console.log('✓ Credentials filled');

    // Step 3: Submit form
    console.log('Step 3: Submitting login form...');
    const signInButton = page.getByRole('button', { name: /sign in/i });
    await expect(signInButton).toBeVisible();

    await signInButton.click();
    console.log('✓ Sign in button clicked');

    // Step 4: Wait for response and check what happens
    await page.waitForTimeout(3000);

    // Check current URL
    const currentUrl = page.url();
    console.log('Current URL:', currentUrl);

    // Check if redirected to dashboard
    if (currentUrl.includes('/staff/dashboard')) {
      console.log('✅ LOGIN SUCCESSFUL - Redirected to dashboard');
      await expect(page.getByText('Dashboard Overview')).toBeVisible({ timeout: 5000 });
    } else if (currentUrl.includes('/staff/login')) {
      console.log('❌ STILL ON LOGIN PAGE - Login failed');

      // Check for error messages on page
      const pageText = await page.textContent('body');
      console.log('Page contains:', pageText?.substring(0, 500));

      // Check for specific error messages
      const errorMessages = [
        'Invalid credentials',
        'Unauthorized',
        'Account locked',
        'User not found',
        'Incorrect password',
      ];

      for (const errorMsg of errorMessages) {
        if (pageText?.includes(errorMsg)) {
          console.log(`❌ Error found: ${errorMsg}`);
        }
      }
    } else {
      console.log(`⚠️ UNEXPECTED REDIRECT: ${currentUrl}`);
    }

    // Step 5: Report findings
    console.log('\n=== INVESTIGATION RESULTS ===');
    console.log(`Console Errors: ${consoleErrors.length}`);
    if (consoleErrors.length > 0) {
      console.log('Errors:', consoleErrors.slice(0, 5));
    }

    console.log(`Failed Requests: ${failedRequests.length}`);
    if (failedRequests.length > 0) {
      console.log('Failed:', failedRequests);
    }

    console.log(`Final URL: ${currentUrl}`);
    console.log('===========================\n');

    // Take screenshot for visual inspection
    await page.screenshot({ path: 'tests/screenshots/staff-login-debug.png', fullPage: true });
    console.log('Screenshot saved to: tests/screenshots/staff-login-debug.png');
  });

  test('should check if staff user exists in database', async ({ page }) => {
    // This test will fail if run standalone, but documents the check
    console.log('Checking if staff user exists...');
    console.log(`Expected username: ${STAFF_USERNAME}`);
    console.log(`Expected role: STAFF, ADMIN, or SUPER_ADMIN`);
    console.log('Run this SQL query to verify:');
    console.log(`SELECT id, email, username, role, isActive FROM users WHERE username = '${STAFF_USERNAME}';`);
  });

  test('should test API login endpoint directly', async ({ request }) => {
    console.log('Testing /api/staff/auth/login endpoint directly...');

    const response = await request.post(`${BASE_URL}/api/staff/auth/login`, {
      data: {
        username: STAFF_USERNAME,
        password: STAFF_PASSWORD,
      },
    });

    console.log('API Response Status:', response.status());

    const responseBody = await response.text();
    console.log('API Response Body:', responseBody);

    if (response.ok()) {
      console.log('✅ API login successful');
      const data = JSON.parse(responseBody);
      console.log('Session created:', data);
    } else {
      console.log('❌ API login failed');
      try {
        const errorData = JSON.parse(responseBody);
        console.log('Error details:', errorData);
      } catch (e) {
        console.log('Raw error:', responseBody);
      }
    }
  });
});
