/**
 * Global Setup for Advanced HVAC Testing
 * 
 * Performs pre-test environment preparation:
 * - Verify staging server accessibility
 * - Check test user account
 * - Clear any existing test data
 * - Set up performance monitoring
 * - Initialize accessibility tools
 */

const { chromium } = require('@playwright/test');
const fs = require('fs');
const path = require('path');

async function globalSetup(config) {
    console.log('🚀 Starting Advanced HVAC E2E Test Suite Setup...');
    
    const STAGING_URL = 'https://upskill-staging.measurequick.com';
    const TEST_USER = 'test_trainer';
    const TEST_PASSWORD = 'TestTrainer123!';
    const REPORTS_DIR = path.join(__dirname, '../../reports');
    
    // Ensure reports directory exists
    if (!fs.existsSync(REPORTS_DIR)) {
        fs.mkdirSync(REPORTS_DIR, { recursive: true });
    }
    
    // Create subdirectories for different report types
    const subdirs = ['screenshots', 'videos', 'traces', 'performance', 'accessibility'];
    subdirs.forEach(subdir => {
        const dirPath = path.join(REPORTS_DIR, subdir);
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath, { recursive: true });
        }
    });
    
    const browser = await chromium.launch({ headless: true });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    try {
        console.log('📡 Checking staging server accessibility...');
        
        // Check if staging server is accessible
        const response = await page.goto(STAGING_URL, { 
            timeout: 30000,
            waitUntil: 'domcontentloaded' 
        });
        
        if (!response || response.status() !== 200) {
            throw new Error(`Staging server not accessible. Status: ${response?.status()}`);
        }
        
        console.log('✅ Staging server is accessible');
        
        // Verify test user can login
        console.log('👤 Verifying test user authentication...');
        
        await page.goto(`${STAGING_URL}/wp-admin`);
        await page.fill('#user_login', TEST_USER);
        await page.fill('#user_pass', TEST_PASSWORD);
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');
        
        // Check if login was successful
        const loginError = await page.locator('#login_error').count();
        if (loginError > 0) {
            throw new Error('Test user login failed - check credentials');
        }
        
        // Check if user has trainer dashboard access
        await page.goto(`${STAGING_URL}/trainer/dashboard/`);
        await page.waitForLoadState('networkidle');
        
        const dashboardTitle = await page.locator('h1, .page-title').count();
        if (dashboardTitle === 0) {
            throw new Error('Test user does not have access to trainer dashboard');
        }
        
        console.log('✅ Test user authentication verified');
        
        // Clean up any previous test events
        console.log('🧹 Cleaning up previous test data...');
        
        try {
            // Navigate to events list if available
            const eventsLink = await page.locator('text=My Events, text=Events, a[href*="event"]').first();
            if (await eventsLink.count() > 0) {
                await eventsLink.click();
                await page.waitForLoadState('networkidle');
                
                // Look for test events and delete them
                const testEvents = await page.locator('text*=Test Event, text*=test, text*=Test').count();
                console.log(`Found ${testEvents} potential test events to clean up`);
                
                // Note: Actual cleanup would require more specific selectors based on the interface
                // This is a placeholder for cleanup logic
            }
        } catch (cleanupError) {
            console.log('⚠️ Cleanup encountered minor issues (non-blocking):', cleanupError.message);
        }
        
        // Initialize performance baseline
        console.log('📊 Setting up performance monitoring...');
        
        const performanceBaseline = await page.evaluate(() => {
            return {
                timestamp: Date.now(),
                userAgent: navigator.userAgent,
                viewport: {
                    width: window.innerWidth,
                    height: window.innerHeight
                },
                connection: navigator.connection ? {
                    effectiveType: navigator.connection.effectiveType,
                    downlink: navigator.connection.downlink
                } : null
            };
        });
        
        // Save baseline data
        fs.writeFileSync(
            path.join(REPORTS_DIR, 'performance', 'baseline.json'),
            JSON.stringify(performanceBaseline, null, 2)
        );
        
        console.log('✅ Performance monitoring initialized');
        
        // Test accessibility tools injection
        console.log('♿ Testing accessibility tools...');
        
        try {
            await page.addScriptTag({ url: 'https://unpkg.com/axe-core@4.7.0/axe.min.js' });
            const axeReady = await page.evaluate(() => {
                return typeof axe !== 'undefined';
            });
            
            if (axeReady) {
                console.log('✅ Accessibility tools ready');
            } else {
                console.log('⚠️ Accessibility tools not available (tests will be skipped)');
            }
        } catch (axeError) {
            console.log('⚠️ Could not load accessibility tools:', axeError.message);
        }
        
        // Create test environment report
        const environmentReport = {
            timestamp: new Date().toISOString(),
            stagingUrl: STAGING_URL,
            testUser: TEST_USER,
            userAgent: await page.evaluate(() => navigator.userAgent),
            viewportSize: await page.viewportSize(),
            browserVersion: browser.version(),
            checks: {
                serverAccessible: true,
                userAuthenticated: true,
                dashboardAccess: true,
                performanceToolsReady: true,
                accessibilityToolsReady: true
            },
            warnings: []
        };
        
        fs.writeFileSync(
            path.join(REPORTS_DIR, 'environment-report.json'),
            JSON.stringify(environmentReport, null, 2)
        );
        
        console.log('✅ Advanced HVAC E2E Test Suite Setup Complete!');
        console.log(`📁 Reports will be saved to: ${REPORTS_DIR}`);
        
    } catch (error) {
        console.error('❌ Setup failed:', error.message);
        
        // Create failure report
        const failureReport = {
            timestamp: new Date().toISOString(),
            error: error.message,
            stack: error.stack,
            url: page.url(),
            screenshot: 'setup-failure.png'
        };
        
        // Take screenshot of failure
        await page.screenshot({
            path: path.join(REPORTS_DIR, 'screenshots', 'setup-failure.png'),
            fullPage: true
        });
        
        fs.writeFileSync(
            path.join(REPORTS_DIR, 'setup-failure.json'),
            JSON.stringify(failureReport, null, 2)
        );
        
        throw error;
    } finally {
        await browser.close();
    }
}

module.exports = globalSetup;