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

test('verify login works', async ({ page }) => {
  // Track requests
  const requests: any[] = [];
  page.on('request', request => {
    if (request.url().includes('auth-token')) {
      requests.push({
        method: request.method(),
        url: request.url(),
        headers: request.headers(),
        body: request.postData()
      });
    }
  });

  const responses: any[] = [];
  page.on('response', async response => {
    if (response.url().includes('auth-token')) {
      const body = await response.text();
      responses.push({
        status: response.status(),
        url: response.url(),
        headers: response.headers(),
        body: body
      });
      console.log('Auth response:', response.status(), body);
    }
  });

  // Go to the app
  await page.goto('http://lvh.me:5174/');

  // Wait for the DevQuickLogin component to load
  await page.waitForSelector('text=Quick Login (Dev Only)', { timeout: 10000 });

  // Click the superuser button
  await page.click('button:has-text("Platform Superuser")');

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

  // Check we got the token
  expect(responses.length).toBeGreaterThan(0);
  expect(responses[0].status).toBe(200);
  expect(responses[0].body).toContain('token');

  console.log('✅ Login successful! Token received:', responses[0].body);

  // Check cookies
  const cookies = await page.context().cookies();
  const accessToken = cookies.find(c => c.name === 'access_token');
  console.log('Access token cookie:', accessToken);

  expect(accessToken).toBeDefined();
  expect(accessToken?.value).toBeTruthy();
});
