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

test('test direct dashboard access after login', async ({ page, context }) => {
  // First, log in via the UI
  console.log('Step 1: Logging in...');
  await page.goto('http://localhost:9000/en/login');

  // Dismiss cookie banner
  try {
    await page.click('text=Accept All', { timeout: 2000 });
  } catch (e) {}

  // Fill and submit
  await page.fill('#identifier', 'gara2222ge@support.com');
  await page.fill('#password', 'eGj&tk!@%T8sFMOq#3QP');
  await page.click('button[type="submit"]');

  console.log('Step 2: Waiting 3 seconds for auth...');
  await page.waitForTimeout(3000);

  // Check cookies
  const cookies = await context.cookies();
  console.log('Cookies after login:', cookies.map(c => c.name).join(', '));

  // Check session via API
  console.log('Step 3: Checking session...');
  const sessionResp = await page.goto('http://localhost:9000/api/auth/session');
  const sessionData = await sessionResp?.json();
  console.log('Session data:', JSON.stringify(sessionData, null, 2));

  if (sessionData?.user) {
    console.log('✅ Session exists - User:', sessionData.user.email);

    // Now try to access dashboard directly
    console.log('Step 4: Navigating to dashboard directly...');
    await page.goto('http://localhost:9000/en/dashboard', { waitUntil: 'networkidle', timeout: 10000 });

    const finalUrl = page.url();
    console.log('Final URL:', finalUrl);

    if (finalUrl.includes('/dashboard')) {
      console.log('✅✅✅ SUCCESS! User CAN access dashboard');
      await page.screenshot({ path: '/tmp/dashboard-success.png' });
    } else if (finalUrl.includes('/login')) {
      console.log('❌ FAILED: Redirected back to login');
      await page.screenshot({ path: '/tmp/dashboard-redirect-login.png' });
    } else {
      console.log('⚠️ Redirected to:', finalUrl);
      await page.screenshot({ path: '/tmp/dashboard-redirect-other.png' });
    }
  } else {
    console.log('❌ No session established after login');
  }
});
