/**
 * Global Test Setup for HVAC Testing Framework
 * 
 * Runs once before all tests to:
 * - Initialize test environment
 * - Pre-generate authentication states
 * - Set up WordPress environment
 * - Verify system health
 * 
 * @package HVAC_Community_Events
 * @version 2.0.0
 * @created 2025-08-27
 */

const { chromium } = require('playwright');
const ConfigManager = require('../core/ConfigManager');
const AuthManager = require('../core/AuthManager');
const WordPressUtils = require('../utils/WordPressUtils');
const fs = require('fs').promises;
const path = require('path');

async function globalSetup(config) {
    console.log('\n🚀 HVAC Testing Framework - Global Setup');
    console.log('='.repeat(50));
    
    const startTime = Date.now();
    const configManager = ConfigManager;
    const authManager = AuthManager;
    const wpUtils = new WordPressUtils();
    
    try {
        // 1. Environment Validation
        console.log('\n📋 1. Validating Environment Configuration');
        
        const environment = configManager.getEnvironment();
        console.log(`   Environment: ${environment}`);
        console.log(`   Base URL: ${configManager.get('app.baseUrl')}`);
        
        // Validate configuration
        configManager.validate();
        console.log('   ✅ Configuration valid');
        
        // 2. WordPress Health Check
        console.log('\n🏥 2. WordPress Health Check');
        
        try {
            const health = await wpUtils.checkHealth();
            console.log('   WordPress Version:', health.wpVersion);
            console.log('   HVAC Plugin Active:', health.pluginsActive ? '✅' : '❌');
            console.log('   Database Connected:', health.databaseConnected ? '✅' : '❌');
            
            if (!health.pluginsActive) {
                console.warn('   ⚠️ HVAC plugin not active - some tests may fail');
            }
        } catch (error) {
            console.warn('   ⚠️ WordPress health check failed:', error.message);
        }
        
        // 3. Create Test Results Directories
        console.log('\n📁 3. Setting Up Test Directories');
        
        const directories = [
            configManager.get('media.screenshotDir'),
            configManager.get('media.videoDir'),
            configManager.get('reporting.outputDir'),
            './test-results/logs',
            './test-results/storage-states'
        ];
        
        for (const dir of directories) {
            await fs.mkdir(dir, { recursive: true });
            console.log(`   ✅ Created: ${dir}`);
        }
        
        // 4. Pre-generate Authentication States
        console.log('\n🔐 4. Pre-generating Authentication States');
        
        if (configManager.get('testData.seedData') && environment !== 'staging') {
            // Only pre-generate auth states in safe environments
            try {
                await authManager.preGenerateStorageStates();
                console.log('   ✅ Authentication states generated');
            } catch (error) {
                console.warn('   ⚠️ Could not pre-generate auth states:', error.message);
                console.warn('   Tests will use fresh login instead');
            }
        } else {
            console.log('   ℹ️ Skipping auth state generation (staging environment)');
        }
        
        // 5. WordPress Environment Preparation
        console.log('\n⚙️ 5. Preparing WordPress Environment');
        
        if (environment === 'local' || environment === 'docker') {
            try {
                // Flush rewrite rules
                await wpUtils.flushRewriteRules();
                console.log('   ✅ Rewrite rules flushed');
                
                // Clear cache
                await wpUtils.clearCache();
                console.log('   ✅ Cache cleared');
                
                // Run cron
                await wpUtils.runCron();
                console.log('   ✅ Cron executed');
                
            } catch (error) {
                console.warn('   ⚠️ WordPress preparation failed:', error.message);
            }
        } else {
            console.log('   ℹ️ Skipping WordPress modifications (staging environment)');
        }
        
        // 6. Browser Verification
        console.log('\n🌐 6. Browser Environment Verification');
        
        const browser = await chromium.launch({
            headless: true,
            timeout: 10000
        });
        
        try {
            const context = await browser.newContext();
            const page = await context.newPage();
            
            // Test basic navigation
            await page.goto(configManager.get('app.baseUrl'), { timeout: 15000 });
            const title = await page.title();
            
            console.log(`   ✅ Site accessible: ${title}`);
            
            await context.close();
        } catch (error) {
            console.error('   ❌ Site not accessible:', error.message);
            throw new Error(`Cannot access test site: ${configManager.get('app.baseUrl')}`);
        } finally {
            await browser.close();
        }
        
        // 7. Generate Setup Report
        console.log('\n📊 7. Generating Setup Report');
        
        const setupReport = {
            timestamp: new Date().toISOString(),
            environment,
            baseUrl: configManager.get('app.baseUrl'),
            configuration: configManager.getAll(),
            setupDuration: Date.now() - startTime,
            directories: directories,
            health: await wpUtils.checkHealth().catch(() => ({ error: 'Health check failed' })),
            authStatesGenerated: true // Will be updated based on actual generation
        };
        
        const reportPath = path.resolve('./test-results/setup-report.json');
        await fs.writeFile(reportPath, JSON.stringify(setupReport, null, 2));
        console.log(`   ✅ Setup report: ${reportPath}`);
        
        // 8. Final Summary
        const duration = ((Date.now() - startTime) / 1000).toFixed(2);
        console.log('\n' + '='.repeat(50));
        console.log('✅ Global Setup Complete');
        console.log(`⏱️  Duration: ${duration}s`);
        console.log(`🌍 Environment: ${environment}`);
        console.log(`🔗 Base URL: ${configManager.get('app.baseUrl')}`);
        console.log('='.repeat(50) + '\n');
        
        return setupReport;
        
    } catch (error) {
        console.error('\n❌ Global Setup Failed');
        console.error('Error:', error.message);
        console.error('='.repeat(50) + '\n');
        throw error;
    }
}

module.exports = globalSetup;