/**
 * Test TEC Community Events as logged in trainer
 */

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

async function loginAsTrainer(page) {
    console.log('🔐 Logging in as test trainer...');
    await page.goto('https://upskill-staging.measurequick.com/trainer/training-login/', {
        waitUntil: 'networkidle',
        timeout: 30000
    });
    
    await page.fill('#username, #user_login, input[name="log"]', 'test_trainer');
    await page.fill('#password, #user_pass, input[name="pwd"]', 'TestTrainer123!');
    await page.click('input[type="submit"], button[type="submit"]');
    await page.waitForTimeout(3000);
    console.log('   ✅ Logged in successfully\n');
}

(async () => {
    const browser = await chromium.launch({ 
        headless: true,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    
    const context = await browser.newContext({
        ignoreHTTPSErrors: true
    });
    
    const page = await context.newPage();
    
    console.log('🔍 TESTING TEC COMMUNITY EVENTS AS LOGGED IN USER');
    console.log('=' .repeat(50));
    
    try {
        await loginAsTrainer(page);
        
        // Check if we're actually logged in
        console.log('📝 Verifying login status...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/dashboard/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        const dashboardCheck = await page.evaluate(() => {
            return {
                isLoggedIn: document.body?.innerText?.includes('test_trainer') || 
                           document.body?.innerText?.includes('Dashboard') ||
                           document.querySelector('.hvac-trainer-menu') !== null,
                pageTitle: document.title
            };
        });
        
        console.log('   Dashboard accessible:', dashboardCheck.isLoggedIn ? '✅' : '❌');
        console.log('   Page title:', dashboardCheck.pageTitle);
        
        // Now try TEC Add Event page
        console.log('\n📝 Navigating to TEC Add Event page...');
        await page.goto('https://upskill-staging.measurequick.com/events/network/add/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        // Check if there's a second login form
        const addEventCheck = await page.evaluate(() => {
            const result = {
                hasLoginForm: document.querySelector('form#tribe_events_community_login') !== null ||
                             document.querySelector('input[name="log"]') !== null,
                hasEventForm: document.querySelector('form#event_form') !== null ||
                             document.querySelector('input[name="post_title"]') !== null ||
                             document.querySelector('#EventTitle') !== null,
                formId: document.querySelector('form')?.id || 'no-form',
                pageText: document.body?.innerText?.substring(0, 300) || ''
            };
            
            // Check for any event-related fields
            const eventFields = [
                'input[name="EventTitle"]',
                'input[name="post_title"]',
                'textarea[name="post_content"]',
                'input[name="EventStartDate"]',
                '#EventTitle',
                '#event_title'
            ];
            
            result.eventFieldsFound = [];
            eventFields.forEach(selector => {
                if (document.querySelector(selector)) {
                    result.eventFieldsFound.push(selector);
                }
            });
            
            return result;
        });
        
        console.log('   Has Login Form:', addEventCheck.hasLoginForm ? '❌ YES (bad)' : '✅ NO');
        console.log('   Has Event Form:', addEventCheck.hasEventForm ? '✅ YES' : '❌ NO');
        console.log('   Form ID:', addEventCheck.formId);
        console.log('   Event Fields Found:', addEventCheck.eventFieldsFound.length > 0 ? 
                    addEventCheck.eventFieldsFound.join(', ') : 'None');
        
        if (addEventCheck.hasLoginForm) {
            console.log('\n⚠️  TEC is showing login form even though user is logged in!');
            console.log('   This suggests:');
            console.log('   - test_trainer may not have the right capabilities');
            console.log('   - TEC Community Events may require specific user roles');
            console.log('   - There may be a session/cookie issue');
        }
        
        // Try to fill in the login form if it exists
        if (addEventCheck.hasLoginForm) {
            console.log('\n📝 Attempting to login through TEC form...');
            await page.fill('input[name="log"]', 'test_trainer');
            await page.fill('input[name="pwd"]', 'TestTrainer123!');
            await page.click('input[name="wp-submit"]');
            await page.waitForTimeout(3000);
            
            // Check again
            const afterLogin = await page.evaluate(() => {
                return {
                    url: window.location.href,
                    hasEventForm: document.querySelector('input[name="post_title"]') !== null ||
                                 document.querySelector('#EventTitle') !== null,
                    pageText: document.body?.innerText?.substring(0, 200) || ''
                };
            });
            
            console.log('   After login URL:', afterLogin.url);
            console.log('   Has Event Form Now:', afterLogin.hasEventForm ? '✅' : '❌');
            console.log('   Page preview:', afterLogin.pageText);
        }
        
    } catch (error) {
        console.error('❌ Error:', error.message);
    } finally {
        await browser.close();
        console.log('\n✅ Test complete');
    }
})();