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

test('diagnose websocket connection', async ({ page }) => {
    test.setTimeout(60000);
    // 1. Go to the platform login page
    console.log('Navigating to login page...');
    await page.goto('http://platform.lvh.me:5173/login');

    // 2. Log in using Quick Login (Platform Superuser)
    await page.getByRole('button', { name: 'Platform Superuser SUPERUSER' }).click();

    // 3. Wait for navigation to dashboard
    await page.waitForURL('**/dashboard');
    console.log('Logged in successfully.');

    // 4. Navigate to support page
    console.log('Navigating to support page...');
    await page.getByRole('link', { name: 'Support' }).click();

    // 5. Monitor WebSocket connections
    const wsPromise = page.waitForEvent('websocket', ws => ws.url().includes('/ws/tickets/'));

    try {
        const ws = await wsPromise;
        console.log('WebSocket created:', ws.url());

        // Wait a bit to see if it stays connected
        await page.waitForTimeout(5000);

        if (ws.isClosed()) {
            console.error('WebSocket is CLOSED.');
            throw new Error('WebSocket connection closed unexpectedly');
        } else {
            console.log('WebSocket is OPEN.');
        }
    } catch (e) {
        console.error('WebSocket error:', e);
        throw e;
    }
});
