/**
 * Authentication System Verification Test
 * 
 * Tests the new shared authentication system to ensure:
 * - All user types can authenticate successfully
 * - State management works correctly
 * - Role-based access is properly enforced
 * - LoginPage class functions correctly
 * - Authentication helpers work as expected
 * 
 * @package HVAC_Community_Events
 * @version 3.0.0
 * @created 2025-08-20
 */

const { test, expect, authHelpers, authScenarios, LoginPage } = require('../helpers/auth-fixtures');
const { getAvailableUserTypes, getUserConfig } = require('../helpers/auth.setup');

// Test configuration
const BASE_URL = process.env.UPSKILL_STAGING_URL || 'https://upskill-staging.measurequick.com';

test.describe('Authentication System Verification', () => {
    test.setTimeout(60000);
    
    test.describe('Basic Authentication Tests', () => {
        test('should authenticate trainer successfully', async ({ page }) => {
            await authHelpers.loginAs(page, 'trainer');
            
            // Verify we're on trainer dashboard
            await expect(page.locator('text=Dashboard, text=Trainer Dashboard')).toBeVisible({ timeout: 10000 });
            
            // Verify URL contains trainer path
            expect(page.url()).toMatch(/trainer\/dashboard/);
        });
        
        test('should authenticate master trainer successfully', async ({ page }) => {
            await authHelpers.loginAs(page, 'master_trainer');
            
            // Verify we're on master trainer dashboard
            await expect(page.locator('text=Master Dashboard, text=Master Trainer')).toBeVisible({ timeout: 10000 });
            
            // Verify URL contains master trainer path
            expect(page.url()).toMatch(/master-trainer\/master-dashboard/);
        });
        
        test('should authenticate admin successfully', async ({ page }) => {
            await authHelpers.loginAs(page, 'admin');
            
            // Verify we're on admin dashboard or redirected appropriately
            const isAdminPage = page.url().includes('/wp-admin/') || 
                              page.url().includes('/trainer/dashboard/') ||
                              page.url().includes('/master-trainer/master-dashboard/');
            expect(isAdminPage).toBeTruthy();
        });
    });
    
    test.describe('LoginPage Class Tests', () => {
        test('should login using LoginPage class', async ({ page }) => {
            const loginPage = new LoginPage(page);
            
            await loginPage.loginAsTrainer();
            
            // Verify authentication
            await expect(page.locator('text=Dashboard')).toBeVisible({ timeout: 10000 });
            expect(page.url()).toMatch(/trainer\/dashboard/);
        });
        
        test('should switch between user roles', async ({ page }) => {
            const loginPage = new LoginPage(page);
            
            // Login as trainer first
            await loginPage.loginAsTrainer();
            await expect(page.locator('text=Dashboard')).toBeVisible({ timeout: 10000 });
            const trainerUrl = page.url();
            
            // Switch to master trainer
            await loginPage.switchUser('trainer', 'master_trainer');
            await expect(page.locator('text=Master Dashboard, text=Master Trainer')).toBeVisible({ timeout: 10000 });
            const masterUrl = page.url();
            
            // Verify different URLs
            expect(trainerUrl).not.toBe(masterUrl);
            expect(masterUrl).toMatch(/master-trainer\/master-dashboard/);
        });
        
        test('should handle login with different credentials', async ({ page }) => {
            const loginPage = new LoginPage(page);
            
            // Test with explicit user types
            await loginPage.login('trainer');
            await loginPage.verifyCurrentUserRole('trainer');
            
            await loginPage.logout();
            
            await loginPage.login('master_trainer');
            await loginPage.verifyCurrentUserRole('master_trainer');
        });
    });
    
    test.describe('User Configuration Tests', () => {
        test('should provide correct user configurations', async ({ page }) => {
            const userTypes = getAvailableUserTypes();
            
            // Verify we have the expected user types
            expect(userTypes).toContain('trainer');
            expect(userTypes).toContain('master_trainer');
            expect(userTypes).toContain('admin');
            
            // Test user config retrieval
            const trainerConfig = getUserConfig('trainer');
            expect(trainerConfig.email).toBeTruthy();
            expect(trainerConfig.password).toBeTruthy();
            expect(trainerConfig.role).toBe('hvac_trainer');
            expect(trainerConfig.dashboardPath).toBe('/trainer/dashboard/');
            
            const masterConfig = getUserConfig('master_trainer');
            expect(masterConfig.role).toBe('hvac_master_trainer');
            expect(masterConfig.dashboardPath).toBe('/master-trainer/master-dashboard/');
        });
    });
    
    test.describe('Role-Based Access Tests', () => {
        test('should access appropriate pages for trainer role', async ({ page }) => {
            await authHelpers.loginAs(page, 'trainer');
            
            const trainerPages = [
                '/trainer/dashboard/',
                '/trainer/profile/',
                '/trainer/events/'
            ];
            
            for (const pagePath of trainerPages) {
                await page.goto(`${BASE_URL}${pagePath}`);
                
                // Should not be redirected to login
                expect(page.url()).not.toContain('/wp-login.php');
                expect(page.url()).not.toContain('/training-login/');
                
                // Page should load successfully
                await expect(page.locator('body')).toBeVisible();
            }
        });
        
        test('should restrict access to admin pages for trainer', async ({ page }) => {
            await authHelpers.loginAs(page, 'trainer');
            
            // Try to access admin page
            const response = await page.goto(`${BASE_URL}/wp-admin/`);
            
            // Should be redirected or access denied
            const isAccessRestricted = page.url().includes('/wp-login.php') ||
                                     page.url().includes('/trainer/') ||
                                     response?.status() >= 400;
            
            expect(isAccessRestricted).toBeTruthy();
        });
    });
    
    test.describe('Authentication State Management', () => {
        test('should handle authentication context properly', async ({ browser }) => {
            // Create multiple contexts to test isolation
            const context1 = await browser.newContext();
            const context2 = await browser.newContext();
            
            const page1 = await context1.newPage();
            const page2 = await context2.newPage();
            
            try {
                // Login different users in different contexts
                await authHelpers.loginAs(page1, 'trainer');
                await authHelpers.loginAs(page2, 'master_trainer');
                
                // Verify each context maintains its own authentication
                await page1.goto(`${BASE_URL}/trainer/dashboard/`);
                await page2.goto(`${BASE_URL}/master-trainer/master-dashboard/`);
                
                // Check both pages are correctly authenticated
                await expect(page1.locator('text=Dashboard')).toBeVisible();
                await expect(page2.locator('text=Master Dashboard, text=Master Trainer')).toBeVisible();
                
                // Verify different URLs
                expect(page1.url()).toMatch(/trainer\/dashboard/);
                expect(page2.url()).toMatch(/master-trainer\/master-dashboard/);
                
            } finally {
                await context1.close();
                await context2.close();
            }
        });
        
        test('should verify authentication persists across page navigations', async ({ page }) => {
            await authHelpers.loginAs(page, 'trainer');
            
            const pages = [
                '/trainer/dashboard/',
                '/trainer/profile/',
                '/trainer/events/',
                '/trainer/certificate-reports/'
            ];
            
            for (const pagePath of pages) {
                await page.goto(`${BASE_URL}${pagePath}`);
                
                // Should remain authenticated
                expect(page.url()).not.toContain('/wp-login.php');
                await expect(page.locator('body')).toBeVisible();
                
                // Should have trainer navigation or content
                const hasTrainerContent = await page.locator('text=Dashboard, .hvac-trainer-nav, nav[class*="hvac"]').count() > 0;
                expect(hasTrainerContent).toBeTruthy();
            }
        });
    });
    
    test.describe('Error Handling Tests', () => {
        test('should handle invalid user type gracefully', async ({ page }) => {
            await expect(async () => {
                await authHelpers.loginAs(page, 'invalid_user_type');
            }).rejects.toThrow();
        });
        
        test('should handle authentication failure scenarios', async ({ page }) => {
            const loginPage = new LoginPage(page);
            
            // This test assumes we can simulate auth failure
            // In practice, you might need to mock failed auth
            try {
                await loginPage.navigateToLogin('trainer');
                
                // Try with invalid credentials (if test accounts support this)
                await loginPage.fillLoginForm('invalid@example.com', 'wrongpassword');
                await expect(async () => {
                    await loginPage.submitLoginForm('trainer');
                }).rejects.toThrow();
                
            } catch (error) {
                // Expected behavior for auth failure
                expect(error.message).toContain('Login failed');
            }
        });
    });
});

// Export test utilities for other tests
module.exports = {
    verifyAuthentication: async (page, userType) => {
        await authHelpers.verifyAuth(page, userType);
    },
    
    quickLogin: async (page, userType = 'trainer') => {
        await authHelpers.loginAs(page, userType);
    }
};