/**
 * Modernized Authentication Test Suite
 * 
 * Demonstrates the new HVAC testing framework with:
 * - BaseTest class usage
 * - AuthManager integration
 * - Page Object Models
 * - Configuration management
 * - WordPress-specific assertions
 * 
 * @package HVAC_Community_Events
 * @version 2.0.0
 * @created 2025-08-27
 * @migrated-from tests/e2e/auth-system-verification.test.js
 */

const BaseTest = require('../../framework/core/BaseTest');
const AuthManager = require('../../framework/core/AuthManager');
const LoginPage = require('../../framework/page-objects/LoginPage');
const TrainerDashboard = require('../../framework/page-objects/TrainerDashboard');

// Create test suite using modernized framework
BaseTest.describe('Authentication System - Modernized', () => {
    let authManager;
    let loginPage;
    let trainerDashboard;
    
    test.beforeAll(async () => {
        console.log('🚀 Initializing Authentication Test Suite');
        authManager = AuthManager;
        
        // Pre-generate storage states for faster test execution
        if (process.env.REGENERATE_AUTH_STATES === 'true') {
            await authManager.preGenerateStorageStates();
        }
    });
    
    test.beforeEach(async ({ page }) => {
        loginPage = new LoginPage(page);
        trainerDashboard = new TrainerDashboard(page);
    });
    
    BaseTest.create(
        'should authenticate trainer with storage state management',
        async (page, testInfo, baseTest) => {
            console.log('🧪 Testing trainer authentication with modern framework');
            
            // Use AuthManager for sophisticated authentication
            const authResult = await authManager.authenticate(page, 'trainer');
            
            expect(authResult.valid).toBe(true);
            expect(authResult.role).toBe('trainer');
            
            // Navigate to dashboard using Page Object Model
            await trainerDashboard.navigate();
            
            // Verify dashboard using POM methods
            await trainerDashboard.verifyDashboard();
            await trainerDashboard.verifyTrainerAccess();
            
            // Assert WordPress-specific conditions
            await baseTest.assertWordPressState(page, {
                authenticated: true,
                role: 'trainer'
            });
            
            console.log('✅ Trainer authentication test completed');
        },
        {
            category: 'authentication',
            priority: 'critical',
            tags: ['auth', 'trainer', 'storage-state'],
            requirements: ['trainer-dashboard-access']
        }
    );
    
    BaseTest.create(
        'should authenticate master trainer with fresh login',
        async (page, testInfo, baseTest) => {
            console.log('🧪 Testing master trainer authentication with fresh login');
            
            // Force fresh login to test login flow
            const authResult = await authManager.authenticate(page, 'masterTrainer', { 
                forceLogin: true 
            });
            
            expect(authResult.method).toBe('fresh-login');
            expect(authResult.valid).toBe(true);
            
            // Verify we're on master dashboard
            await baseTest.waitForWordPress(page, 'ready');
            expect(page.url()).toMatch(/master-trainer\/master-dashboard/);
            
            // Check for master trainer navigation
            await expect(page.locator('.hvac-master-dashboard, .master-trainer-nav')).toBeVisible();
            
            // Verify master trainer access levels
            await baseTest.assertWordPressState(page, {
                authenticated: true,
                role: 'masterTrainer'
            });
            
            console.log('✅ Master trainer authentication test completed');
        },
        {
            category: 'authentication',
            priority: 'critical',
            tags: ['auth', 'master-trainer', 'fresh-login'],
            requirements: ['master-dashboard-access']
        }
    );
    
    BaseTest.create(
        'should handle authentication failures gracefully',
        async (page, testInfo, baseTest) => {
            console.log('🧪 Testing authentication failure handling');
            
            // Navigate to login page
            await loginPage.navigateToLogin('trainer');
            
            // Attempt login with invalid credentials
            await loginPage.fillLoginForm('invalid_user', 'invalid_password');
            
            try {
                await loginPage.submitLoginForm('trainer');
                
                // Should throw error or show error message
                await loginPage.checkForLoginErrors();
                
                // Should still be on login page
                expect(page.url()).toMatch(/training-login|wp-login/);
                
                console.log('✅ Authentication failure handled correctly');
            } catch (error) {
                // This is expected for invalid credentials
                console.log('✅ Authentication failed as expected:', error.message);
                expect(error.message).toMatch(/Login failed/);
            }
        },
        {
            category: 'authentication',
            priority: 'high',
            tags: ['auth', 'error-handling', 'security'],
            requirements: ['login-error-handling']
        }
    );
    
    BaseTest.create(
        'should enforce role-based access control',
        async (page, testInfo, baseTest) => {
            console.log('🧪 Testing role-based access control');
            
            // Authenticate as trainer
            await authManager.authenticate(page, 'trainer');
            
            // Try to access master trainer page (should fail)
            await page.goto('/master-trainer/trainers/');
            
            // Should either redirect to login or show access denied
            const currentUrl = page.url();
            const hasAccessDenied = await page.locator('text=Access denied, text=Permission denied, text=You do not have permission').isVisible().catch(() => false);
            const redirectedToLogin = currentUrl.includes('/training-login/') || currentUrl.includes('/wp-login.php');
            
            expect(hasAccessDenied || redirectedToLogin).toBe(true);
            
            // Verify trainer can access their own pages
            await trainerDashboard.navigate();
            await trainerDashboard.verifyTrainerAccess();
            
            console.log('✅ Role-based access control working correctly');
        },
        {
            category: 'authentication',
            priority: 'critical',
            tags: ['auth', 'rbac', 'security'],
            requirements: ['role-based-access-control']
        }
    );
    
    BaseTest.create(
        'should maintain session across page navigation',
        async (page, testInfo, baseTest) => {
            console.log('🧪 Testing session persistence');
            
            // Authenticate as trainer
            await authManager.authenticate(page, 'trainer');
            
            // Navigate through multiple pages
            const pages = [
                '/trainer/dashboard/',
                '/trainer/profile/',
                '/trainer/events/',
                '/trainer/venues/'
            ];
            
            for (const pagePath of pages) {
                await page.goto(pagePath);
                await baseTest.waitForWordPress(page, 'ready');
                
                // Verify we're still authenticated
                const isAuthenticated = await baseTest.page.evaluate(() => {
                    return document.body.classList.contains('logged-in') ||
                           document.querySelector('#wpadminbar') !== null ||
                           document.querySelector('.hvac-trainer-nav') !== null;
                });
                
                expect(isAuthenticated).toBe(true);
                console.log(`✅ Session maintained on: ${pagePath}`);
            }
            
            console.log('✅ Session persistence test completed');
        },
        {
            category: 'authentication',
            priority: 'medium',
            tags: ['auth', 'session', 'navigation'],
            requirements: ['session-persistence']
        }
    );
    
    BaseTest.create(
        'should handle logout correctly',
        async (page, testInfo, baseTest) => {
            console.log('🧪 Testing logout functionality');
            
            // Authenticate as trainer
            await authManager.authenticate(page, 'trainer');
            await trainerDashboard.navigate();
            
            // Verify we're logged in
            await trainerDashboard.verifyTrainerAccess();
            
            // Perform logout
            await authManager.logout(page);
            
            // Verify we're logged out
            const isLoggedOut = page.url().includes('/wp-login.php') || 
                               page.url().includes('/training-login/') ||
                               page.url().includes('/logged-out');
            
            expect(isLoggedOut).toBe(true);
            
            // Try to access protected page - should redirect to login
            await page.goto('/trainer/dashboard/');
            await baseTest.waitForWordPress(page, 'ready');
            
            const redirectedToLogin = page.url().includes('/training-login/') || 
                                    page.url().includes('/wp-login.php');
            
            expect(redirectedToLogin).toBe(true);
            
            console.log('✅ Logout functionality working correctly');
        },
        {
            category: 'authentication',
            priority: 'high',
            tags: ['auth', 'logout', 'security'],
            requirements: ['logout-functionality']
        }
    );
    
    test.afterAll(async () => {
        // Generate authentication status report
        const authStatus = await authManager.getAuthStatus();
        console.log('📊 Authentication Status Report:', authStatus);
        
        // Clear validation cache for next run
        authManager.clearValidationCache();
        
        console.log('✅ Authentication Test Suite completed');
    });
});