#!/usr/bin/env node

/**
 * Quick Docker Environment Verification Script
 * Tests basic functionality of Docker WordPress setup
 */

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

// Configuration
const CONFIG = {
    baseURL: process.env.BASE_URL || 'http://localhost:8080',
    headless: process.env.HEADLESS !== 'false',
    timeout: 30000,
};

console.log('🔍 HVAC Docker Environment Verification');
console.log('========================================');
console.log(`📍 Target: ${CONFIG.baseURL}`);
console.log(`🖥️  Mode: ${CONFIG.headless ? 'Headless' : 'Headed'}`);
console.log('========================================');

async function verifyEnvironment() {
    const browser = await chromium.launch({ 
        headless: CONFIG.headless,
        timeout: CONFIG.timeout 
    });
    
    const context = await browser.newContext();
    const page = await context.newPage();
    
    try {
        // Test 1: Basic WordPress accessibility
        console.log('🧪 Test 1: WordPress Accessibility...');
        await page.goto(CONFIG.baseURL, { timeout: CONFIG.timeout });
        
        const title = await page.title();
        console.log(`✅ WordPress accessible - Title: ${title}`);
        
        // Test 2: Admin area accessibility
        console.log('🧪 Test 2: Admin Area...');
        await page.goto(`${CONFIG.baseURL}/wp-admin/`, { timeout: CONFIG.timeout });
        
        // Should see login form or dashboard
        const hasLogin = await page.locator('#loginform').isVisible().catch(() => false);
        const hasAdminBar = await page.locator('#wpadminbar').isVisible().catch(() => false);
        
        if (hasLogin || hasAdminBar) {
            console.log('✅ Admin area accessible');
        } else {
            console.log('⚠️  Admin area response unexpected');
        }
        
        // Test 3: Plugin check
        console.log('🧪 Test 3: HVAC Plugin Check...');
        await page.goto(`${CONFIG.baseURL}/wp-admin/plugins.php`, { timeout: CONFIG.timeout });
        
        // Look for HVAC plugin in page content
        const content = await page.content();
        const hasHVACPlugin = content.includes('hvac-community-events') || content.includes('HVAC Community Events');
        
        if (hasHVACPlugin) {
            console.log('✅ HVAC plugin detected');
        } else {
            console.log('⚠️  HVAC plugin not detected in plugins page');
        }
        
        // Test 4: Try HVAC pages
        console.log('🧪 Test 4: HVAC Pages...');
        
        const hvacPages = [
            '/trainer/dashboard/',
            '/master-trainer/master-dashboard/',
            '/training-login/'
        ];
        
        for (const pagePath of hvacPages) {
            try {
                const response = await page.goto(`${CONFIG.baseURL}${pagePath}`, { 
                    timeout: 10000,
                    waitUntil: 'networkidle' 
                });
                
                if (response.status() === 200) {
                    console.log(`✅ ${pagePath} - accessible`);
                } else if (response.status() === 302 || response.status() === 301) {
                    console.log(`➡️  ${pagePath} - redirects (likely auth required)`);
                } else {
                    console.log(`⚠️  ${pagePath} - Status: ${response.status()}`);
                }
            } catch (error) {
                console.log(`❌ ${pagePath} - Error: ${error.message.substring(0, 50)}...`);
            }
        }
        
        // Test 5: Login test with test user
        console.log('🧪 Test 5: Test User Login...');
        try {
            await page.goto(`${CONFIG.baseURL}/wp-login.php`, { timeout: CONFIG.timeout });
            
            // Fill login form
            await page.fill('#user_login', 'test_master');
            await page.fill('#user_pass', 'TestMaster123!');
            await page.click('#wp-submit');
            
            await page.waitForLoadState('networkidle', { timeout: 10000 });
            
            const currentUrl = page.url();
            if (currentUrl.includes('wp-admin')) {
                console.log('✅ Test user login successful');
                
                // Try accessing master trainer dashboard while logged in
                await page.goto(`${CONFIG.baseURL}/master-trainer/master-dashboard/`, { timeout: 10000 });
                const pageTitle = await page.title();
                console.log(`📊 Master Dashboard - Title: ${pageTitle}`);
                
            } else {
                console.log('⚠️  Login may have failed - not redirected to admin');
            }
        } catch (error) {
            console.log(`❌ Login test failed: ${error.message.substring(0, 50)}...`);
        }
        
        console.log('\n🏁 Environment Verification Complete');
        console.log('====================================');
        console.log('💡 Status: Docker environment is set up');
        console.log(`📋 Admin Access: ${CONFIG.baseURL}/wp-admin/ (admin/admin123)`);
        console.log(`👤 Test User: ${CONFIG.baseURL}/wp-admin/ (test_master/TestMaster123!)`);
        console.log(`📊 PhpMyAdmin: http://localhost:8081`);
        console.log(`📧 MailHog: http://localhost:8025`);
        
        return true;
        
    } catch (error) {
        console.log(`❌ Verification failed: ${error.message}`);
        return false;
    } finally {
        await browser.close();
    }
}

// Run verification
verifyEnvironment()
    .then(success => {
        if (success) {
            console.log('\n✅ Environment verification passed');
            process.exit(0);
        } else {
            console.log('\n❌ Environment verification failed');
            process.exit(1);
        }
    })
    .catch(error => {
        console.error(`❌ Fatal error: ${error.message}`);
        process.exit(1);
    });