/**
 * Playwright Configuration for Master Trainer Comprehensive Tests
 * 
 * Agent C Implementation - Configuration optimized for comprehensive testing
 * of all 12 Master Trainer administrative pages
 * 
 * Features:
 * - GNOME session support with Xwayland
 * - WordPress error detection
 * - Comprehensive screenshot capture
 * - MCP Playwright tools integration
 * - Staging environment optimization
 * 
 * @package HVAC_Community_Events
 * @version 2.0.0
 * @created 2025-08-27
 */

const { defineConfig, devices } = require('@playwright/test');

// Environment configuration
const isGnomeDesktop = process.env.XDG_CURRENT_DESKTOP === 'GNOME';
const hasDisplay = process.env.DISPLAY || process.env.WAYLAND_DISPLAY;
const useHeaded = !process.env.CI && process.env.HEADLESS !== 'true' && isGnomeDesktop && hasDisplay;

// Base URL and credentials
const baseUrl = process.env.BASE_URL || 'https://upskill-staging.measurequick.com';

module.exports = defineConfig({
  // Test discovery and execution
  testDir: './e2e',
  testMatch: '**/master-trainer-comprehensive.test.js',
  
  // Execution settings
  fullyParallel: false, // Sequential execution for master trainer workflows
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 1,
  workers: 1, // Single worker to avoid conflicts
  
  // Timeout settings
  timeout: 300000, // 5 minutes per test
  expect: {
    timeout: 30000 // 30 seconds for assertions
  },
  
  // Output and reporting
  outputDir: './test-results/master-trainer-comprehensive',
  reporter: [
    ['html', { 
      outputFolder: './test-results/html-report',
      open: useHeaded ? 'always' : 'never'
    }],
    ['json', { 
      outputFile: './test-results/master-trainer-results.json' 
    }],
    ['junit', { 
      outputFile: './test-results/junit-results.xml' 
    }],
    ['line'] // Console output
  ],
  
  // Global settings
  use: {
    // Base URL for tests
    baseURL: baseUrl,
    
    // Browser settings
    headless: !useHeaded,
    slowMo: useHeaded ? 500 : 0, // Slow motion for visual debugging
    
    // Viewport
    viewport: { width: 1920, height: 1080 }, // Full HD for comprehensive testing
    
    // Screenshots and videos
    screenshot: 'only-on-failure',
    video: useHeaded ? 'on' : 'retain-on-failure',
    trace: 'retain-on-failure',
    
    // Navigation and timeouts
    navigationTimeout: 60000, // 1 minute for page loads
    actionTimeout: 30000, // 30 seconds for actions
    
    // WordPress-specific settings
    extraHTTPHeaders: {
      'User-Agent': 'HVAC-Master-Trainer-E2E-Tests/2.0 Playwright',
      'X-Test-Framework': 'HVAC-WordPress-Tests',
      'X-Test-Suite': 'Master-Trainer-Comprehensive'
    },
    
    // Ignore SSL errors for staging environment
    ignoreHTTPSErrors: true,
    
    // Accept insecure certs
    acceptDownloads: true
  },
  
  // Test projects (browsers)
  projects: [
    {
      name: 'chromium-headed',
      use: { 
        ...devices['Desktop Chrome'],
        channel: 'chrome', // Use system Chrome if available
        launchOptions: useHeaded ? {
          args: [
            '--start-maximized',
            '--disable-web-security', // For staging testing
            '--disable-features=TranslateUI',
            '--disable-dev-shm-usage',
            '--no-sandbox'
          ],
          slowMo: 500
        } : undefined
      },
      testMatch: useHeaded ? '**/*.test.js' : undefined
    },
    
    {
      name: 'chromium-headless',
      use: { 
        ...devices['Desktop Chrome'],
        launchOptions: {
          args: [
            '--disable-dev-shm-usage',
            '--no-sandbox',
            '--disable-setuid-sandbox'
          ]
        }
      },
      testMatch: !useHeaded ? '**/*.test.js' : undefined
    }
  ],
  
  // Global setup and teardown
  globalSetup: useHeaded ? undefined : require.resolve('./framework/setup/global-setup.js'),
  globalTeardown: useHeaded ? undefined : require.resolve('./framework/setup/global-teardown.js'),
  
  // Test environment setup
  webServer: process.env.CI ? undefined : {
    // Only run web server in CI environment
    command: 'echo "Using external staging server"',
    url: baseUrl,
    reuseExistingServer: true,
    timeout: 10000
  },
  
  // WordPress-specific test metadata
  metadata: {
    testSuite: 'Master Trainer Comprehensive E2E Tests',
    framework: 'HVAC Testing Framework 2.0',
    targetUrl: baseUrl,
    coverage: {
      totalPages: 12,
      targetPages: [
        'master-trainer/master-dashboard/',
        'master-trainer/events/',
        'master-trainer/trainers/',
        'master-trainer/announcements/',
        'master-trainer/pending-approvals/',
        'master-trainer/communication-templates/',
        'master-trainer/google-sheets/',
        'master-trainer/import-export/'
      ]
    },
    testAccounts: [
      'test_master/TestMaster123!',
      'JoeMedosch@gmail.com/JoeTrainer2025@'
    ],
    testCategories: [
      'Analytics Validation',
      'Events Management',
      'Trainer Management', 
      'System Administration',
      'Layout Consistency',
      'Security Validation',
      'Mobile Responsiveness'
    ]
  }
});

// Environment-specific logging
console.log('🔧 Playwright Configuration Loaded');
console.log(`📍 Base URL: ${baseUrl}`);
console.log(`🖥️  Desktop: ${process.env.XDG_CURRENT_DESKTOP || 'unknown'}`);
console.log(`📺 Display: ${process.env.DISPLAY || 'none'} (Wayland: ${process.env.WAYLAND_DISPLAY || 'none'})`);
console.log(`🎥 Mode: ${useHeaded ? 'Headed' : 'Headless'}`);
console.log(`🧪 Test File: master-trainer-comprehensive.test.js`);