import { chromium } from 'playwright';

async function testLoginFlow() {
  console.log('Starting login flow test...');
  
  // Launch browser
  const browser = await chromium.launch({ 
    headless: false,
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });
  
  const context = await browser.newContext({
    recordVideo: { dir: './test-recordings/' }
  });
  
  const page = await context.newPage();
  
  // Enable console logging
  page.on('console', msg => console.log('BROWSER:', msg.text()));
  
  // Monitor network requests
  page.on('request', request => {
    if (request.url().includes('/api/auth/')) {
      console.log('AUTH REQUEST:', request.method(), request.url());
    }
  });
  
  page.on('response', response => {
    if (response.url().includes('/api/auth/')) {
      console.log('AUTH RESPONSE:', response.status(), response.url());
    }
  });
  
  try {
    console.log('Navigating to login page...');
    await page.goto('http://localhost:3000/login');
    
    // Take screenshot of initial state
    await page.screenshot({ path: './test-recordings/01-login-page.png' });
    console.log('Screenshot 1: Login page loaded');
    
    // Wait for page to load completely
    await page.waitForLoadState('networkidle');
    
    // Take screenshot after loading
    await page.screenshot({ path: './test-recordings/02-after-loading.png' });
    console.log('Screenshot 2: After page load complete');
    
    // Fill in login form
    console.log('Filling login form...');
    await page.fill('#email', 'tmartinez@gmail.com');
    await page.fill('#password', 'Skittles@420');
    
    // Take screenshot of filled form
    await page.screenshot({ path: './test-recordings/03-form-filled.png' });
    console.log('Screenshot 3: Form filled');
    
    // Get cookies before login
    const cookiesBefore = await context.cookies();
    console.log('Cookies before login:', cookiesBefore.map(c => ({ name: c.name, value: c.value.substring(0, 20) + '...' })));
    
    // Submit form
    console.log('Submitting login form...');
    await page.click('button[type="submit"]');
    
    // Wait for navigation or response
    await page.waitForTimeout(2000);
    
    // Take screenshot after submit
    await page.screenshot({ path: './test-recordings/04-after-submit.png' });
    console.log('Screenshot 4: After form submit');
    
    // Get cookies after login
    const cookiesAfter = await context.cookies();
    console.log('Cookies after login:', cookiesAfter.map(c => ({ name: c.name, value: c.value.substring(0, 20) + '...' })));
    
    // Wait for any redirects
    await page.waitForTimeout(3000);
    
    // Check current URL
    const currentURL = page.url();
    console.log('Current URL after login:', currentURL);
    
    // Take final screenshot
    await page.screenshot({ path: './test-recordings/05-final-state.png' });
    console.log('Screenshot 5: Final state');
    
    // If we're on dashboard, success!
    if (currentURL.includes('/dashboard')) {
      console.log('✅ SUCCESS: Redirected to dashboard');
    } else if (currentURL.includes('/login')) {
      console.log('❌ FAILED: Still on login page (loop detected)');
    } else {
      console.log('❓ UNEXPECTED: Redirected to', currentURL);
    }
    
  } catch (error) {
    console.error('Test failed:', error);
    await page.screenshot({ path: './test-recordings/error.png' });
  } finally {
    await browser.close();
    console.log('Test completed. Check ./test-recordings/ for screenshots and video.');
  }
}

// Run the test
testLoginFlow().catch(console.error);