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

test('Debug WebSocket connection', async ({ page }) => {
  const consoleMessages: string[] = [];
  const wsMessages: string[] = [];

  // Capture all console messages
  page.on('console', msg => {
    const text = `[${msg.type()}] ${msg.text()}`;
    consoleMessages.push(text);
    if (msg.text().includes('WebSocket')) {
      console.log(text);
    }
  });

  // Capture page errors
  page.on('pageerror', error => {
    console.log('Page error:', error.message);
  });

  // Navigate to event page
  await page.goto('/events/1', { waitUntil: 'networkidle' });
  await page.waitForTimeout(3000);

  // Check console for WebSocket messages
  console.log('\n=== All Console Messages ===');
  consoleMessages.forEach(msg => console.log(msg));

  // Take screenshot
  await page.screenshot({ path: 'test-results/websocket-debug.png', fullPage: true });

  // Check for WebSocket related logs
  const wsLogs = consoleMessages.filter(m => m.toLowerCase().includes('websocket') || m.toLowerCase().includes('ws://') || m.toLowerCase().includes('wss://'));
  console.log('\n=== WebSocket Related Logs ===');
  wsLogs.forEach(msg => console.log(msg));
});

test('Check WebSocket URL configuration', async ({ page }) => {
  // Navigate and check what WS_URL is being used
  await page.goto('/events/1');

  const wsUrl = await page.evaluate(() => {
    // @ts-ignore
    return window.__WS_URL__ || 'not exposed';
  });
  console.log('WS_URL from window:', wsUrl);

  // Check environment variables
  const envCheck = await page.evaluate(() => {
    return {
      // @ts-ignore
      VITE_WS_URL: import.meta?.env?.VITE_WS_URL,
      // @ts-ignore
      VITE_API_URL: import.meta?.env?.VITE_API_URL,
    };
  });
  console.log('Environment variables:', envCheck);
});

test('Test WebSocket endpoint directly', async ({ page, request }) => {
  // First check if backend is running
  try {
    const healthCheck = await request.get('http://localhost:8000/api/v1/sport-events');
    console.log('Backend health check status:', healthCheck.status());
  } catch (e) {
    console.log('Backend not reachable:', e);
  }

  // Try to connect to WebSocket from browser
  await page.goto('/events/1');

  const wsResult = await page.evaluate(async () => {
    return new Promise((resolve) => {
      const ws = new WebSocket('ws://localhost:8000/api/v1/ws?token=guest&event_id=1');

      ws.onopen = () => {
        resolve({ status: 'connected', readyState: ws.readyState });
        ws.close();
      };

      ws.onerror = (e) => {
        resolve({ status: 'error', error: 'Connection failed' });
      };

      ws.onclose = (e) => {
        if (e.code !== 1000) {
          resolve({ status: 'closed', code: e.code, reason: e.reason });
        }
      };

      // Timeout after 5 seconds
      setTimeout(() => {
        resolve({ status: 'timeout', readyState: ws.readyState });
        ws.close();
      }, 5000);
    });
  });

  console.log('WebSocket connection result:', wsResult);
});
