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

test('Debug login flow for guqo@mailinator.com', async ({ page }) => {
  // Listen for console messages
  page.on('console', msg => {
    console.log(`[BROWSER ${msg.type().toUpperCase()}]:`, msg.text());
  });

  // Listen for network requests
  page.on('request', request => {
    if (request.url().includes('/api/')) {
      console.log(`[REQUEST] ${request.method()} ${request.url()}`);
    }
  });

  // Listen for responses
  page.on('response', async response => {
    if (response.url().includes('/api/auth/login')) {
      console.log(`[RESPONSE] ${response.status()} ${response.url()}`);
      try {
        const body = await response.json();
        console.log('[RESPONSE BODY]:', JSON.stringify(body, null, 2));
      } catch (e) {
        console.log('[RESPONSE] Could not parse JSON');
      }
    }
  });

  // Navigate to login page
  console.log('\n=== Navigating to login page ===');
  await page.goto('http://localhost:9000/en/login');
  await page.waitForLoadState('networkidle');

  // Take screenshot of initial state
  await page.screenshot({ path: '/tmp/login-initial.png' });
  console.log('Screenshot saved: /tmp/login-initial.png');

  // Fill in email
  console.log('\n=== Filling in email ===');
  await page.fill('input[type="text"]', 'guqo@mailinator.com');

  // Wait a bit
  await page.waitForTimeout(1000);

  // Click Send OTP button
  console.log('\n=== Clicking Send OTP button ===');
  const sendButton = page.locator('button[type="submit"]').first();
  await sendButton.click();

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

  // Take screenshot after submission
  await page.screenshot({ path: '/tmp/login-after-submit.png' });
  console.log('Screenshot saved: /tmp/login-after-submit.png');

  // Check for error message
  const errorElement = page.locator('text=/Internal server error|Failed to send/i');
  const hasError = await errorElement.count() > 0;

  if (hasError) {
    const errorText = await errorElement.textContent();
    console.log(`\n❌ ERROR FOUND: ${errorText}`);
  }

  // Check if OTP step appeared
  const otpInput = page.locator('input[maxlength="6"]');
  const hasOTPInput = await otpInput.count() > 0;

  if (hasOTPInput) {
    console.log('\n✅ OTP input appeared - login request succeeded!');
  } else {
    console.log('\n❌ OTP input did NOT appear - login request failed');
  }

  // Get final page state
  console.log('\n=== Final Page State ===');
  const pageContent = await page.textContent('body');
  if (pageContent.includes('Internal server error')) {
    console.log('❌ Internal server error message present');
  }
  if (pageContent.includes('verification code sent')) {
    console.log('✅ Success message present');
  }
});
