/**
 * Environment Configuration Manager
 * Centralized configuration management for different environments
 */

const path = require('path');

class EnvironmentConfig {
    constructor(environment = 'staging') {
        this.environment = environment;
        this.config = null;
        this.loadConfiguration();
    }

    /**
     * Load configuration for specified environment
     * @returns {void}
     */
    loadConfiguration() {
        try {
            const configFile = path.join(__dirname, `${this.environment}.config.js`);
            this.config = require(configFile);
        } catch (error) {
            console.warn(`Failed to load config for ${this.environment}, using default staging`);
            this.config = require('./staging.config.js');
        }
    }

    /**
     * Get full configuration object
     * @returns {Object}
     */
    getConfig() {
        return this.config;
    }

    /**
     * Get browser configuration
     * @returns {Object}
     */
    getBrowserConfig() {
        return {
            browserType: 'chromium',
            headless: this.config.browser?.headless ?? true,
            slowMo: this.config.browser?.slowMo ?? 0,
            timeout: this.config.framework?.timeout ?? 30000,
            viewport: this.config.browser?.viewport ?? { width: 1280, height: 720 },
            video: this.config.framework?.videosOnFailure ?? false,
            screenshot: this.config.framework?.screenshotsOnFailure ? 'only-on-failure' : 'off',
            args: this.config.browser?.args ?? []
        };
    }

    /**
     * Get authentication configuration
     * @returns {Object}
     */
    getAuthConfig() {
        return {
            baseUrl: this.config.app?.baseUrl || this.config.baseUrl,
            loginPath: this.config.urls?.login || this.config.wordpress?.customLoginPath || '/community-login/',
            logoutPath: this.config.urls?.wpLogin || '/wp-login.php?action=logout'
        };
    }

    /**
     * Get test user accounts
     * @returns {Object}
     */
    getUserAccounts() {
        if (this.config.environments?.users) {
            // New format
            return {
                masterTrainer: this.config.environments.users.masterTrainer,
                alternateMasterTrainer: this.config.environments.users.masterTrainerAlt,
                trainer: this.config.environments.users.trainer,
                admin: this.config.environments.users.admin
            };
        } else if (this.config.accounts) {
            // Legacy format
            return this.config.accounts;
        } else {
            // Fallback defaults
            return {
                masterTrainer: {
                    username: 'test_master',
                    password: 'TestMaster123!',
                    email: 'test_master@example.com',
                    role: 'master_trainer'
                },
                trainer: {
                    username: 'test_trainer',
                    password: 'TestTrainer123!',
                    email: 'test_trainer@example.com',
                    role: 'hvac_trainer'
                }
            };
        }
    }

    /**
     * Get test execution configuration
     * @returns {Object}
     */
    getTestConfig() {
        return {
            timeout: this.config.framework?.timeout ?? this.config.test?.timeout ?? 30000,
            retries: this.config.framework?.retries ?? this.config.test?.retries ?? 2,
            parallel: this.config.framework?.parallel ?? this.config.test?.parallel ?? false,
            workers: this.config.framework?.maxWorkers ?? this.config.test?.workers ?? 1,
            screenshotOnFailure: this.config.framework?.screenshotsOnFailure ?? this.config.test?.screenshotOnFailure ?? true,
            videoOnFailure: this.config.framework?.videosOnFailure ?? this.config.test?.videoOnFailure ?? false
        };
    }

    /**
     * Get protected URLs for security testing
     * @returns {string[]}
     */
    getProtectedUrls() {
        if (this.config.protectedUrls) {
            return this.config.protectedUrls;
        }

        // Default protected URLs
        return [
            '/trainer/dashboard/',
            '/trainer/venue/list/',
            '/trainer/venue/manage/', 
            '/trainer/organizer/manage/',
            '/trainer/profile/training-leads/',
            '/master-trainer/master-dashboard/',
            '/master-trainer/events/',
            '/master-trainer/google-sheets/',
            '/master-trainer/announcements/',
            '/master-trainer/pending-approvals/',
            '/master-trainer/trainers/',
            '/master-trainer/communication-templates/'
        ];
    }

    /**
     * Get test data configuration
     * @returns {Object}
     */
    getTestDataConfig() {
        return {
            seedData: this.config.testData?.seedData ?? true,
            cleanupAfterTests: this.config.testData?.cleanupAfterTests ?? true,
            isolateTransactions: this.config.testData?.isolateTransactions ?? true,
            fixtures: this.config.testData?.fixtures ?? {}
        };
    }

    /**
     * Get evidence collection configuration
     * @returns {Object}
     */
    getEvidenceConfig() {
        return {
            screenshots: {
                enabled: this.config.evidence?.screenshots?.enabled ?? true,
                onFailure: this.config.evidence?.screenshots?.onFailure ?? true,
                onSuccess: this.config.evidence?.screenshots?.onSuccess ?? false,
                fullPage: this.config.evidence?.screenshots?.fullPage ?? true,
                dir: this.config.media?.screenshotDir ?? './tests/evidence/screenshots'
            },
            videos: {
                enabled: this.config.evidence?.videos?.enabled ?? false,
                onFailure: this.config.evidence?.videos?.onFailure ?? true,
                onSuccess: this.config.evidence?.videos?.onSuccess ?? false,
                dir: this.config.media?.videoDir ?? './tests/evidence/videos'
            },
            logs: {
                enabled: this.config.evidence?.logs?.enabled ?? true,
                level: this.config.evidence?.logs?.level ?? 'info',
                includeNetwork: this.config.evidence?.logs?.includeNetwork ?? true,
                includeConsole: this.config.evidence?.logs?.includeConsole ?? true
            }
        };
    }

    /**
     * Get WordPress-specific configuration
     * @returns {Object}
     */
    getWordPressConfig() {
        return {
            cliPath: this.config.wordpress?.cliPath ?? 'wp',
            adminPath: this.config.wordpress?.adminPath ?? '/wp-admin/',
            apiPath: this.config.wordpress?.apiPath ?? '/wp-json/',
            databaseIsolation: this.config.wordpress?.databaseIsolation ?? true,
            flushRewriteRules: this.config.wordpress?.flushRewriteRules ?? true,
            clearCache: this.config.wordpress?.clearCache ?? true
        };
    }

    /**
     * Get security configuration
     * @returns {Object}
     */
    getSecurityConfig() {
        return {
            allowInsecureCertificates: this.config.security?.allowInsecureCertificates ?? true,
            ignoreHttpsErrors: this.config.network?.ignoreHTTPSErrors ?? true,
            skipCsrfValidation: this.config.security?.skipCsrfValidation ?? false,
            bypassCSP: this.config.network?.bypassCSP ?? false
        };
    }

    /**
     * Get base URL for the environment
     * @returns {string}
     */
    getBaseUrl() {
        return this.config.app?.baseUrl || this.config.baseUrl || 'https://upskill-staging.measurequick.com';
    }

    /**
     * Get environment name
     * @returns {string}
     */
    getEnvironmentName() {
        return this.config.name || this.config.app?.environment || this.environment;
    }

    /**
     * Check if feature is enabled
     * @param {string} featureName - Name of feature to check
     * @returns {boolean}
     */
    isFeatureEnabled(featureName) {
        return this.config.features?.[featureName] ?? true;
    }

    /**
     * Get environment-specific selectors
     * @returns {Object}
     */
    getSelectors() {
        return this.config.selectors ?? {
            dataTestIdAttribute: 'data-testid',
            roleAttribute: 'data-role',
            pageAttribute: 'data-page'
        };
    }

    /**
     * Get expected content for validation
     * @returns {Object}
     */
    getExpectedContent() {
        return this.config.expectedContent ?? {};
    }

    /**
     * Get performance configuration
     * @returns {Object}
     */
    getPerformanceConfig() {
        return {
            slowNetworkSimulation: this.config.performance?.slowNetworkSimulation ?? false,
            resourceBlocking: this.config.performance?.resourceBlocking ?? {
                images: false,
                fonts: false,
                stylesheets: false
            }
        };
    }
}

/**
 * Create environment configuration instance
 * @param {string} environment - Environment name
 * @returns {EnvironmentConfig}
 */
function createEnvironmentConfig(environment = process.env.TEST_ENVIRONMENT || 'staging') {
    return new EnvironmentConfig(environment);
}

module.exports = { EnvironmentConfig, createEnvironmentConfig };