/**
 * Quick authentication debug test
 */

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

async function testAuth() {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage();
  
  try {
    // Navigate to login page
    await page.goto('https://upskill-staging.measurequick.com/training-login/');
    await page.waitForLoadState('networkidle');
    
    console.log('Current URL after navigation:', page.url());
    
    if (page.url().includes('/trainer/')) {
      console.log('✅ Already logged in - session exists');
      
      // Let's logout first
      try {
        await page.goto('https://upskill-staging.measurequick.com/wp-login.php?action=logout');
        await page.waitForLoadState('networkidle');
        console.log('✅ Logged out');
      } catch (e) {
        console.log('⚠️  Logout attempt:', e.message);
      }
      
      // Try again
      await page.goto('https://upskill-staging.measurequick.com/training-login/');
      await page.waitForLoadState('networkidle');
    }
    
    console.log('Login page URL:', page.url());
    
    // Check if login form exists
    const loginForm = await page.locator('#user_login').count();
    console.log('Login form present:', loginForm > 0);
    
    if (loginForm > 0) {
      // Try test_trainer credentials
      console.log('\n🔐 Testing test_trainer credentials...');
      await page.fill('#user_login', 'test_trainer');
      await page.fill('#user_pass', 'TestTrainer123!');
      await page.click('#wp-submit');
      await page.waitForLoadState('networkidle');
      await page.waitForTimeout(3000);
      
      const afterLoginUrl = page.url();
      console.log('After login URL:', afterLoginUrl);
      
      if (afterLoginUrl.includes('login=failed')) {
        console.log('❌ test_trainer login failed');
        
        // Try alternative credentials
        await page.goto('https://upskill-staging.measurequick.com/training-login/');
        await page.waitForLoadState('networkidle');
        
        console.log('\n🔐 Testing alternative credentials...');
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');
        await page.waitForTimeout(3000);
        
        const altLoginUrl = page.url();
        console.log('Alternative login URL:', altLoginUrl);
        
        if (altLoginUrl.includes('/trainer/')) {
          console.log('✅ Alternative credentials worked!');
        } else {
          console.log('❌ Alternative credentials failed');
        }
      } else if (afterLoginUrl.includes('/trainer/')) {
        console.log('✅ test_trainer login successful');
      }
    }
    
  } catch (error) {
    console.error('Debug test failed:', error.message);
  } finally {
    await browser.close();
  }
}

testAuth().catch(console.error);