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

(async () => {
    console.log('🚀 Starting Final Verification Test Suite');
    console.log('=====================================\n');
    
    const browser = await chromium.launch({ 
        headless: true,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    
    const context = await browser.newContext({
        viewport: { width: 1280, height: 720 }
    });
    
    const page = await context.newPage();
    const baseUrl = 'https://upskill-staging.measurequick.com';
    
    let passedTests = 0;
    let failedTests = 0;
    const results = [];
    
    async function testPage(name, url, checkContent = true) {
        console.log(`Testing: ${name}`);
        try {
            const response = await page.goto(baseUrl + url, { 
                waitUntil: 'domcontentloaded', 
                timeout: 30000 
            });
            
            if (!response || response.status() >= 400) {
                throw new Error(`HTTP ${response ? response.status() : 'unknown'}`);
            }
            
            // Wait a bit for content to load
            await page.waitForTimeout(2000);
            
            if (checkContent) {
                const content = await page.textContent('body');
                if (content.includes('Page not found') || 
                    content.includes('404') || 
                    content.trim().length < 100) {
                    throw new Error('Page appears empty or missing');
                }
            }
            
            passedTests++;
            results.push({ name, status: 'PASSED' });
            console.log(`  ✅ ${name} - PASSED\n`);
        } catch (error) {
            failedTests++;
            results.push({ name, status: 'FAILED', error: error.message });
            console.log(`  ❌ ${name} - FAILED: ${error.message}\n`);
        }
    }
    
    // Test 1: Public Pages
    console.log('📋 Test 1: Public Pages\n');
    await testPage('Login Page', '/training-login/');
    
    // Test 2: Trainer Pages (Previously Empty - No Auth Required for Basic Check)
    console.log('📋 Test 2: Trainer Pages (Previously Empty)\n');
    await testPage('Venue List Page', '/trainer/venue/list/');
    await testPage('Venue Manage Page', '/trainer/venue/manage/');
    await testPage('Organizer Manage Page', '/trainer/organizer/manage/');
    await testPage('Training Leads Page', '/trainer/profile/training-leads/');
    
    // Test 3: Master Trainer Pages
    console.log('📋 Test 3: Master Trainer Pages\n');
    await testPage('Master Dashboard', '/master-trainer/master-dashboard/');
    await testPage('Master Google Sheets', '/master-trainer/google-sheets/');
    await testPage('Master Announcements', '/master-trainer/announcements/');
    await testPage('Master Pending Approvals', '/master-trainer/pending-approvals/');
    await testPage('Master Trainers Overview', '/master-trainer/trainers/');
    
    // Test 4: Check for specific elements
    console.log('📋 Test 4: Element Verification\n');
    
    // Check login page has form
    await page.goto(baseUrl + '/training-login/', { waitUntil: 'domcontentloaded' });
    const hasLoginForm = await page.locator('form').count() > 0;
    if (hasLoginForm) {
        console.log('  ✅ Login form present');
        passedTests++;
    } else {
        console.log('  ❌ Login form missing');
        failedTests++;
    }
    
    // Check if trainer pages have navigation (may require auth)
    await page.goto(baseUrl + '/trainer/venue/list/', { waitUntil: 'domcontentloaded' });
    await page.waitForTimeout(2000);
    const pageContent = await page.textContent('body');
    
    if (pageContent.includes('log in') || pageContent.includes('Login')) {
        console.log('  ⚠️  Pages require authentication (expected behavior)');
    } else if (pageContent.includes('venue') || pageContent.includes('Venue')) {
        console.log('  ✅ Venue page has content');
        passedTests++;
    }
    
    // Summary
    console.log('\n=====================================');
    console.log('📊 FINAL VERIFICATION SUMMARY');
    console.log('=====================================');
    console.log(`✅ Passed: ${passedTests}`);
    console.log(`❌ Failed: ${failedTests}`);
    console.log(`📊 Success Rate: ${Math.round((passedTests / (passedTests + failedTests)) * 100)}%\n`);
    
    console.log('Detailed Results:');
    results.forEach(result => {
        const icon = result.status === 'PASSED' ? '✅' : '❌';
        console.log(`${icon} ${result.name}: ${result.status}`);
        if (result.error) {
            console.log(`   Error: ${result.error}`);
        }
    });
    
    await browser.close();
    
    console.log('\n📝 NOTES:');
    console.log('- Pages may require authentication for full content');
    console.log('- AJAX content may load after initial page load');
    console.log('- Master trainer pages require specific role permissions');
    
    if (failedTests > 5) {
        console.log('\n⚠️  Multiple tests failed. Please review manually.');
        process.exit(1);
    } else {
        console.log('\n✅ Verification complete. Most pages are loading.');
    }
})();