#!/usr/bin/env node

/**
 * Quick validation test for critical fixes deployed to staging
 * Tests the most important improvements from the refactoring
 */

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

const STAGING_URL = 'https://upskill-staging.measurequick.com';
const TEST_USERS = {
    trainer: {
        username: 'test_trainer',
        password: 'TestTrainer123!'
    },
    master: {
        username: 'test_master', 
        password: 'TestMaster123!'
    }
};

async function runTests() {
    console.log('🚀 HVAC Plugin Critical Fixes Validation');
    console.log('=========================================\n');
    
    const browser = await chromium.launch({ 
        headless: false, // Run in headed mode
        slowMo: 500 // Slow down for visibility
    });
    
    const context = await browser.newContext({
        viewport: { width: 1920, height: 1080 }
    });
    const page = await context.newPage();
    
    const results = {
        passed: [],
        failed: []
    };
    
    try {
        // Test 1: CSS Consolidation - Should load much faster
        console.log('📊 Test 1: CSS Consolidation (was 250+ files, now 5)');
        await page.goto(STAGING_URL + '/training-login/');
        
        // Count CSS requests
        const cssRequests = [];
        page.on('response', response => {
            if (response.url().includes('.css')) {
                cssRequests.push(response.url());
            }
        });
        
        await page.reload();
        await page.waitForTimeout(3000);
        
        const hvacCssFiles = cssRequests.filter(url => url.includes('hvac'));
        console.log(`   CSS files loaded: ${hvacCssFiles.length}`);
        
        if (hvacCssFiles.length <= 10) {
            console.log('   ✅ PASS: CSS consolidation working (${hvacCssFiles.length} files)\n');
            results.passed.push('CSS Consolidation');
        } else {
            console.log(`   ❌ FAIL: Too many CSS files (${hvacCssFiles.length})\n`);
            results.failed.push('CSS Consolidation');
        }
        
        // Test 2: Login Flow (Security framework)
        console.log('🔐 Test 2: Authentication (New security framework)');
        await page.goto(STAGING_URL + '/training-login/');
        
        // Try to access dashboard without login
        await page.goto(STAGING_URL + '/trainer/dashboard/');
        await page.waitForTimeout(2000);
        
        if (page.url().includes('login')) {
            console.log('   ✅ PASS: Unauthorized access redirects to login\n');
            results.passed.push('Security - Auth redirect');
        } else {
            console.log('   ❌ FAIL: Dashboard accessible without login\n');
            results.failed.push('Security - Auth redirect');
        }
        
        // Test 3: Login and Dashboard Access
        console.log('🚪 Test 3: Login and Dashboard Access');
        await page.goto(STAGING_URL + '/training-login/');
        
        // Look for login form
        const loginForm = await page.$('#hvac-login-form, form[name="loginform"], .hvac-login-form');
        
        if (loginForm) {
            // Try to fill and submit
            await page.fill('input[name="log"], input[name="username"], #username', TEST_USERS.trainer.username);
            await page.fill('input[name="pwd"], input[name="password"], #password', TEST_USERS.trainer.password);
            
            // Click login button
            await Promise.all([
                page.waitForNavigation({ timeout: 10000 }).catch(() => {}),
                page.click('input[type="submit"], button[type="submit"]')
            ]);
            
            await page.waitForTimeout(3000);
            
            if (page.url().includes('dashboard')) {
                console.log('   ✅ PASS: Login successful, dashboard accessible\n');
                results.passed.push('Login flow');
                
                // Test 4: Check for PHP errors
                console.log('⚠️  Test 4: PHP Stability (No segfaults)');
                const bodyText = await page.textContent('body');
                
                if (!bodyText.includes('Fatal error') && !bodyText.includes('Warning:')) {
                    console.log('   ✅ PASS: No PHP errors detected\n');
                    results.passed.push('PHP Stability');
                } else {
                    console.log('   ❌ FAIL: PHP errors found on page\n');
                    results.failed.push('PHP Stability');
                }
                
                // Test 5: Performance - Page Load Time
                console.log('⚡ Test 5: Performance (Should be 85% faster)');
                const startTime = Date.now();
                await page.reload();
                await page.waitForLoadState('networkidle');
                const loadTime = Date.now() - startTime;
                
                console.log(`   Page load time: ${loadTime}ms`);
                if (loadTime < 3000) {
                    console.log('   ✅ PASS: Page loads quickly\n');
                    results.passed.push('Performance');
                } else {
                    console.log('   ⚠️  WARN: Page load slower than expected\n');
                    results.failed.push('Performance');
                }
                
            } else {
                console.log('   ❌ FAIL: Login failed or redirect issue\n');
                results.failed.push('Login flow');
            }
        } else {
            console.log('   ⚠️  SKIP: Could not find login form\n');
        }
        
        // Test 6: Safari Stability (via WebKit)
        console.log('🌐 Test 6: Safari/WebKit Stability');
        console.log('   Note: Testing with Chromium, but CSS fixes should prevent Safari crashes\n');
        
        // Test 7: Event Management
        console.log('📅 Test 7: Event Management (Unified system)');
        await page.goto(STAGING_URL + '/trainer/event/manage/');
        await page.waitForTimeout(2000);
        
        const eventContent = await page.textContent('body');
        if (eventContent.includes('event') || eventContent.includes('Event')) {
            console.log('   ✅ PASS: Event management page loads\n');
            results.passed.push('Event Management');
        } else {
            console.log('   ⚠️  WARN: Could not verify event management\n');
        }
        
    } catch (error) {
        console.error('❌ Test Error:', error.message);
    } finally {
        // Summary
        console.log('\n' + '='.repeat(50));
        console.log('📊 TEST RESULTS SUMMARY');
        console.log('='.repeat(50));
        console.log(`✅ Passed: ${results.passed.length} tests`);
        results.passed.forEach(test => console.log(`   • ${test}`));
        
        console.log(`\n❌ Failed: ${results.failed.length} tests`);
        results.failed.forEach(test => console.log(`   • ${test}`));
        
        const passRate = (results.passed.length / (results.passed.length + results.failed.length)) * 100;
        console.log(`\n🎯 Pass Rate: ${passRate.toFixed(1)}%`);
        
        if (passRate >= 80) {
            console.log('✅ DEPLOYMENT VALIDATION: SUCCESS');
        } else {
            console.log('⚠️  DEPLOYMENT VALIDATION: NEEDS ATTENTION');
        }
        
        await browser.close();
    }
}

// Run the tests
runTests().catch(console.error);