import { test, expect } from '@playwright/test';

test('Login and Dashboard Deep Test', async ({ page }) => {
    console.log('=== Testing Login and Dashboard for Critical Errors ===');
    
    // Test multiple login scenarios to trigger potential errors
    const loginAttempts = [
        { username: 'test_trainer', password: 'Test123!', name: 'test_trainer' },
        { username: 'devadmin', password: 'zc3CQlCOr9ZZBZDakecTqcOt', name: 'devadmin' },
        { username: 'invalid_user', password: 'wrong_pass', name: 'invalid' }
    ];
    
    for (const attempt of loginAttempts) {
        console.log(`\n--- Testing login with ${attempt.name} ---`);
        
        try {
            // Clear cookies and storage
            await page.context().clearCookies();
            await page.evaluate(() => localStorage.clear());
            await page.evaluate(() => sessionStorage.clear());
            
            // Go to community login
            await page.goto('https://upskill-staging.measurequick.com/community-login/', { waitUntil: 'networkidle' });
            
            // Fill login form
            await page.fill('#user_login', attempt.username);
            await page.fill('#user_pass', attempt.password);
            await page.click('#wp-submit');
            
            await page.waitForLoadState('networkidle');
            
            console.log(`  URL after login: ${page.url()}`);
            
            // Check for any critical errors
            const hasCriticalError = await page.locator('text=critical error').count() > 0;
            const hasWordPressFatalError = await page.locator('text=There has been a critical error').count() > 0;
            const hasPhpError = await page.locator('text=Fatal error').count() > 0;
            const hasParseError = await page.locator('text=Parse error').count() > 0;
            const hasCallStackError = await page.locator('text=Call Stack').count() > 0;
            
            if (hasCriticalError || hasWordPressFatalError || hasPhpError || hasParseError || hasCallStackError) {
                console.log(`  ❌ CRITICAL ERROR DETECTED for ${attempt.name}`);
                
                // Get full page text for analysis
                const bodyText = await page.locator('body').textContent();
                const errorLines = bodyText?.split('\n').filter(line => 
                    line.includes('Fatal') || 
                    line.includes('critical') ||
                    line.includes('Error') ||
                    line.includes('Call Stack') ||
                    line.includes('.php')
                ).slice(0, 15) || [];
                
                console.log('  Error details:');
                errorLines.forEach((line, i) => {
                    if (line.trim()) console.log(`    ${i + 1}: ${line.trim()}`);
                });
                
                await page.screenshot({ 
                    path: `critical-error-login-${attempt.name}.png`,
                    fullPage: true 
                });
            } else {
                console.log(`  ✅ No critical error for ${attempt.name}`);
            }
            
            // If login successful, try to access dashboard
            if (page.url().includes('hvac-dashboard') || !page.url().includes('login')) {
                console.log(`  Successful login for ${attempt.name}, testing dashboard...`);
                
                // Navigate to dashboard directly
                await page.goto('https://upskill-staging.measurequick.com/hvac-dashboard/', { waitUntil: 'networkidle' });
                
                const dashboardHasError = await page.locator('text=critical error').count() > 0 ||
                                         await page.locator('text=There has been a critical error').count() > 0;
                
                if (dashboardHasError) {
                    console.log(`  ❌ DASHBOARD ERROR for ${attempt.name}`);
                    await page.screenshot({ 
                        path: `dashboard-error-${attempt.name}.png`,
                        fullPage: true 
                    });
                } else {
                    console.log(`  ✅ Dashboard loads without error for ${attempt.name}`);
                }
                
                // Test certificate reports
                await page.goto('https://upskill-staging.measurequick.com/certificate-reports/', { waitUntil: 'networkidle' });
                
                const certHasError = await page.locator('text=critical error').count() > 0 ||
                                    await page.locator('text=There has been a critical error').count() > 0;
                
                if (certHasError) {
                    console.log(`  ❌ CERTIFICATE REPORTS ERROR for ${attempt.name}`);
                    await page.screenshot({ 
                        path: `cert-reports-error-${attempt.name}.png`,
                        fullPage: true 
                    });
                } else {
                    console.log(`  ✅ Certificate reports loads without error for ${attempt.name}`);
                }
            }
            
        } catch (error) {
            console.log(`  ❌ Exception during ${attempt.name} test: ${error}`);
            await page.screenshot({ 
                path: `exception-${attempt.name}.png`
            });
        }
    }
    
    // Test admin area with different credentials
    console.log(`\n--- Testing WP Admin Access ---`);
    
    try {
        await page.context().clearCookies();
        await page.goto('https://upskill-staging.measurequick.com/wp-admin/', { waitUntil: 'networkidle' });
        
        // Try admin login with the API credentials
        await page.fill('#user_login', 'devadmin');
        await page.fill('#user_pass', 'zc3CQlCOr9ZZBZDakecTqcOt');
        await page.click('#wp-submit');
        
        await page.waitForLoadState('networkidle');
        
        console.log(`  Admin area URL: ${page.url()}`);
        
        const adminHasError = await page.locator('text=critical error').count() > 0 ||
                             await page.locator('text=There has been a critical error').count() > 0;
        
        if (adminHasError) {
            console.log(`  ❌ ADMIN AREA ERROR`);
            await page.screenshot({ 
                path: `admin-area-error.png`,
                fullPage: true 
            });
        } else {
            console.log(`  ✅ Admin area loads without error`);
        }
        
    } catch (error) {
        console.log(`  ❌ Exception during admin test: ${error}`);
    }
    
    console.log('\n=== Login and Dashboard Test Complete ===');
});