/**
 * Test authenticated access to trainer pages
 */

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

async function testAuthAccess() {
    console.log('🔍 Testing Authenticated Access...\\n');
    
    const browser = await chromium.launch({
        headless: false,
        args: ['--disable-dev-shm-usage', '--no-sandbox']
    });
    
    const context = await browser.newContext({
        viewport: { width: 1280, height: 720 }
    });
    
    const page = await context.newPage();
    const baseUrl = 'https://upskill-staging.measurequick.com';
    
    try {
        // Step 1: Login first
        console.log('1️⃣ Logging in...');
        await page.goto(`${baseUrl}/training-login/`);
        await page.waitForLoadState('networkidle');
        
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        
        console.log('   Submitting login...');
        await page.press('input[name="pwd"]', 'Enter');
        
        // Wait for redirect and check if successful
        try {
            await page.waitForURL('**/trainer/dashboard/**', { timeout: 10000 });
            console.log('✅ Login successful - redirected to dashboard');
        } catch {
            // Check current URL
            const currentUrl = page.url();
            console.log('   Current URL after login attempt:', currentUrl);
            
            if (currentUrl.includes('training-login')) {
                console.log('❌ Login failed - still on login page');
                return;
            } else {
                console.log('✅ Login successful - different redirect');
            }
        }
        
        // Wait for page to fully load
        await page.waitForLoadState('networkidle');
        
        // Step 2: Test if we can access trainer pages while logged in
        console.log('\\n2️⃣ Testing authenticated access to trainer pages...');
        
        const testPages = [
            { url: '/trainer/dashboard/', name: 'Dashboard' },
            { url: '/trainer/event/manage/', name: 'Event Manage' },
            { url: '/trainer/event/edit/', name: 'Event Edit' },
            { url: '/trainer/certificate-reports/', name: 'Certificate Reports' }
        ];
        
        for (const testPage of testPages) {
            console.log(`\\n   Testing: ${testPage.name} (${testPage.url})`);
            
            await page.goto(`${baseUrl}${testPage.url}`);
            await page.waitForLoadState('networkidle', { timeout: 10000 });
            
            const result = await page.evaluate(() => {
                const currentUrl = window.location.href;
                const hasLoginForm = document.querySelector('input[name="log"]') !== null;
                const hasTrainerNav = document.querySelector('.hvac-navigation-wrapper') !== null;
                const hasEventForm = document.querySelector('.hvac-event-form, .tribe-community-events') !== null;
                const title = document.title;
                
                return { 
                    currentUrl, 
                    hasLoginForm, 
                    hasTrainerNav, 
                    hasEventForm,
                    title
                };
            });
            
            console.log(`     Final URL: ${result.currentUrl}`);
            console.log(`     Title: ${result.title}`);
            console.log(`     Redirected to login: ${result.hasLoginForm}`);
            console.log(`     Has trainer navigation: ${result.hasTrainerNav}`);
            console.log(`     Has event form: ${result.hasEventForm}`);
            
            if (result.hasLoginForm) {
                console.log('     ❌ ACCESS DENIED - redirected to login');
            } else if (result.hasTrainerNav) {
                console.log('     ✅ ACCESS GRANTED - showing trainer content');
            } else {
                console.log('     ⚠️ UNKNOWN - page loaded but content unclear');
            }
        }
        
        // Step 3: Check authentication status
        console.log('\\n3️⃣ Checking authentication status...');
        
        await page.goto(`${baseUrl}/trainer/dashboard/`);
        await page.waitForLoadState('networkidle');
        
        const authStatus = await page.evaluate(() => {
            // Check for user info in the page
            const body = document.body.innerHTML;
            const hasLogout = body.includes('logout') || body.includes('Logout');
            const hasWelcome = body.includes('Welcome') || body.includes('welcome');
            const hasUserName = body.includes('test_trainer') || body.includes('Test Trainer');
            
            // Check for WordPress authentication
            const hasAdminBar = document.querySelector('#wpadminbar') !== null;
            const hasLoginForm = document.querySelector('input[name="log"]') !== null;
            
            return {
                hasLogout,
                hasWelcome,
                hasUserName,
                hasAdminBar,
                hasLoginForm,
                currentUrl: window.location.href
            };
        });
        
        console.log('   Current URL:', authStatus.currentUrl);
        console.log('   Has logout link:', authStatus.hasLogout);
        console.log('   Has welcome message:', authStatus.hasWelcome);
        console.log('   Has username:', authStatus.hasUserName);
        console.log('   Has admin bar:', authStatus.hasAdminBar);
        console.log('   Has login form:', authStatus.hasLoginForm);
        
        if (authStatus.hasLoginForm) {
            console.log('\\n❌ AUTHENTICATION FAILED - user is not logged in');
        } else if (authStatus.hasLogout || authStatus.hasAdminBar) {
            console.log('\\n✅ AUTHENTICATION SUCCESSFUL - user is logged in');
        } else {
            console.log('\\n⚠️ AUTHENTICATION UNCLEAR - mixed signals');
        }
        
        // Take final screenshot
        await page.screenshot({ 
            path: `auth-access-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('\\n📸 Screenshot saved');
        
    } catch (error) {
        console.error('\\n❌ Test failed:', error.message);
        
        await page.screenshot({ 
            path: `error-auth-access-${Date.now()}.png`,
            fullPage: true 
        });
    } finally {
        console.log('\\n⏸️ Keeping browser open for inspection...');
        await page.waitForTimeout(10000);
        await browser.close();
    }
}

// Run test
testAuthAccess()
    .then(() => {
        console.log('\\n✨ Test completed!');
        process.exit(0);
    })
    .catch(error => {
        console.error('\\n💥 Test failed:', error);
        process.exit(1);
    });