const { chromium } = require('playwright');
const fs = require('fs');

async function testAuthenticationFlow() {
  const browser = await chromium.launch({ 
    headless: false, // Set to false to see what's happening
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });
  
  const context = await browser.newContext({
    viewport: { width: 1280, height: 1024 }
  });
  
  const page = await context.newPage();
  
  console.log('🔍 Testing authentication flow...');
  
  try {
    // Step 1: Try to access protected route (should redirect to login)
    console.log('\n1️⃣ Attempting to access protected route...');
    await page.goto('http://192.168.0.46:3000/events/7ac12bd2-8509-4db3-b1bc-98a808646311/manage');
    await page.waitForTimeout(2000);
    
    const currentUrl = page.url();
    console.log('Current URL:', currentUrl);
    
    if (currentUrl.includes('/login')) {
      console.log('✅ Correctly redirected to login page');
    } else {
      console.log('❌ Did not redirect to login page');
      await page.screenshot({ path: 'debug-unexpected-page.png' });
      return;
    }
    
    // Step 2: Fill in login form
    console.log('\n2️⃣ Attempting login...');
    
    // Check if we need to accept cookies first
    const cookieBanner = await page.$('#cookie-consent-banner');
    if (cookieBanner) {
      console.log('Accepting cookies...');
      await page.click('#cookie-accept-btn');
      await page.waitForTimeout(1000);
    }
    
    // Fill login form with test credentials
    const emailInput = await page.$('#email');
    const passwordInput = await page.$('#password');
    
    if (!emailInput || !passwordInput) {
      console.log('❌ Login form not found');
      await page.screenshot({ path: 'debug-no-login-form.png' });
      return;
    }
    
    // Use test credentials from create-test-user.cjs
    await page.fill('#email', 'tmartinez@gmail.com');
    await page.fill('#password', 'TestPassword123!');
    
    console.log('Submitting login form...');
    await page.click('#login-btn');
    
    // Wait for navigation or error
    await page.waitForTimeout(3000);
    
    const postLoginUrl = page.url();
    console.log('Post-login URL:', postLoginUrl);
    
    // Check if login was successful
    if (postLoginUrl.includes('/dashboard') || postLoginUrl.includes('/events/')) {
      console.log('✅ Login appears successful - redirected to protected area');
      
      // Step 3: Try to access the original protected route
      console.log('\n3️⃣ Accessing original protected route...');
      await page.goto('http://192.168.0.46:3000/events/7ac12bd2-8509-4db3-b1bc-98a808646311/manage');
      await page.waitForTimeout(3000);
      
      const finalUrl = page.url();
      console.log('Final URL:', finalUrl);
      
      if (finalUrl.includes('/events/') && finalUrl.includes('/manage')) {
        console.log('✅ Successfully accessed event management page!');
        
        // Check for expected components
        const hasEventManagement = await page.$('.event-management, [data-testid="event-management"]');
        const hasCards = await page.$('.card, .glassmorphism');
        
        console.log('Component check:', {
          hasEventManagement: !!hasEventManagement,
          hasCards: !!hasCards
        });
        
        await page.screenshot({ path: 'debug-success-page.png' });
        
      } else {
        console.log('❌ Still redirected away from event management page');
        await page.screenshot({ path: 'debug-still-redirected.png' });
      }
      
    } else if (postLoginUrl.includes('/login')) {
      console.log('❌ Login failed - still on login page');
      
      // Check for error messages
      const errorMessage = await page.$('.error, [id*="error"]');
      if (errorMessage) {
        const errorText = await errorMessage.textContent();
        console.log('Error message:', errorText);
      }
      
      await page.screenshot({ path: 'debug-login-failed.png' });
      
    } else {
      console.log('🤔 Unexpected post-login behavior');
      console.log('Current page title:', await page.title());
      await page.screenshot({ path: 'debug-unexpected-login.png' });
    }
    
  } catch (error) {
    console.error('❌ Test failed with error:', error);
    await page.screenshot({ path: 'debug-test-error.png' });
  } finally {
    await browser.close();
  }
}

// Helper function to test with different credentials
async function testWithCredentials(email, password) {
  console.log(`\n🧪 Testing with credentials: ${email}`);
  
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext();
  const page = await context.newPage();
  
  try {
    await page.goto('http://192.168.0.46:3000/login');
    await page.waitForTimeout(1000);
    
    // Accept cookies if needed
    const cookieBanner = await page.$('#cookie-consent-banner');
    if (cookieBanner) {
      await page.click('#cookie-accept-btn');
      await page.waitForTimeout(500);
    }
    
    await page.fill('#email', email);
    await page.fill('#password', password);
    await page.click('#login-btn');
    
    await page.waitForTimeout(3000);
    
    const url = page.url();
    const success = !url.includes('/login');
    
    console.log(`Result: ${success ? '✅ Success' : '❌ Failed'} - ${url}`);
    
    return success;
    
  } catch (error) {
    console.log(`❌ Error: ${error.message}`);
    return false;
  } finally {
    await browser.close();
  }
}

console.log('🚀 Starting authentication flow test...');
testAuthenticationFlow()
  .then(() => {
    console.log('\n✨ Test completed');
  })
  .catch(error => {
    console.error('💥 Test suite failed:', error);
    process.exit(1);
  });