const { chromium } = require('playwright');

async function testMasterTrainerEditFix() {
    console.log('🔍 TESTING MASTER TRAINER PROFILE EDIT FIX');
    console.log('================================================================================');
    
    const browser = await chromium.launch({ headless: false });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    try {
        // Login as master trainer
        console.log('📝 Logging in as master trainer...');
        await page.goto('https://upskill-staging.measurequick.com/wp-login.php');
        await page.fill('#user_login', 'JoeMedosch@gmail.com');
        await page.fill('#user_pass', 'JoeTrainer2025@');
        await page.click('#wp-submit');
        await page.waitForURL('**/master-trainer/master-dashboard/**', { timeout: 15000 });
        console.log('✅ Master trainer login successful');
        
        // Test the direct URL first
        console.log('🔍 Testing master trainer profile edit URL directly...');
        const testUrl = 'https://upskill-staging.measurequick.com/master-trainer/trainer-profile/edit?user_id=42';
        await page.goto(testUrl);
        await page.waitForLoadState('networkidle');
        
        const directTestResult = await page.evaluate(() => {
            return {
                url: window.location.href,
                title: document.title,
                hasEditForm: document.querySelector('#hvac-master-profile-form') !== null,
                hasTrainerFields: document.querySelectorAll('input, select, textarea').length,
                hasPermissionError: document.body.innerText.includes('master trainer') && document.body.innerText.includes('access'),
                isNotFound: document.body.innerText.includes("doesn't seem to exist") || document.title.includes('not found'),
                hasProfileHeader: document.querySelector('.hvac-page-header h1') !== null,
                profileHeaderText: document.querySelector('.hvac-page-header h1')?.textContent || 'none',
                contentPreview: document.body.innerText.slice(0, 400).replace(/\\s+/g, ' ').trim()
            };
        });
        
        console.log('📊 Direct URL test results:', directTestResult);
        
        if (directTestResult.hasEditForm) {
            console.log('✅ Master trainer profile edit page is now working!');
            
            // Test form functionality
            console.log('🔍 Testing form fields and functionality...');
            
            const formDetails = await page.evaluate(() => {
                const form = document.querySelector('#hvac-master-profile-form');
                if (!form) return { error: 'No form found' };
                
                return {
                    hasNonce: document.querySelector('input[name="hvac_profile_nonce"]') !== null,
                    hasUserIdField: document.querySelector('input[name="edit_user_id"]') !== null,
                    hasProfileIdField: document.querySelector('input[name="profile_id"]') !== null,
                    hasCertificationFields: document.querySelector('#certification_status') !== null,
                    hasPersonalFields: document.querySelector('#trainer_first_name') !== null,
                    hasBusinessFields: document.querySelector('#business_type') !== null,
                    hasLocationFields: document.querySelector('#trainer_city') !== null,
                    hasSaveButton: document.querySelector('button[type="submit"]') !== null,
                    saveButtonText: document.querySelector('button[type="submit"]')?.textContent || 'none',
                    formSections: [...document.querySelectorAll('.hvac-form-section h3')].map(h => h.textContent),
                    userIdValue: document.querySelector('input[name="edit_user_id"]')?.value || 'none'
                };
            });
            
            console.log('📝 Form details:', formDetails);
            
            // Test if it's loading the correct user's data
            if (formDetails.userIdValue === '42') {
                console.log('✅ Correct user ID is loaded in the form');
            }
            
            await page.screenshot({ path: 'master-trainer-edit-working.png', fullPage: true });
            
        } else if (directTestResult.isNotFound) {
            console.log('❌ Page still showing "not found" error');
        } else {
            console.log('⚠️ Different issue - check content preview');
        }
        
        // Test clicking from master dashboard
        console.log('🔍 Testing access from master dashboard...');
        await page.goto('https://upskill-staging.measurequick.com/master-trainer/master-dashboard/');
        await page.waitForLoadState('networkidle');
        
        // Look for trainer links
        const trainerLinks = await page.evaluate(() => {
            const links = [...document.querySelectorAll('a[href*="trainer-profile/edit"]')];
            return links.slice(0, 3).map(link => ({
                text: link.textContent.trim(),
                href: link.href
            }));
        });
        
        console.log('👥 Found trainer links:', trainerLinks);
        
        if (trainerLinks.length > 0) {
            console.log(`🔍 Testing first trainer link: ${trainerLinks[0].text}`);
            await page.goto(trainerLinks[0].href);
            await page.waitForLoadState('networkidle');
            
            const linkTestResult = await page.evaluate(() => {
                return {
                    url: window.location.href,
                    title: document.title,
                    hasEditForm: document.querySelector('#hvac-master-profile-form') !== null,
                    hasTrainerName: document.querySelector('.hvac-page-header h1')?.textContent.includes('Edit Trainer Profile:') || false,
                    trainerName: document.querySelector('.hvac-page-header h1')?.textContent || 'none'
                };
            });
            
            console.log('🔗 Link click test result:', linkTestResult);
            
            if (linkTestResult.hasEditForm) {
                console.log('✅ Master trainer can successfully edit trainer profiles via dashboard links!');
            }
            
            await page.screenshot({ path: 'master-trainer-dashboard-link-test.png', fullPage: true });
        }
        
        console.log('================================================================================');
        console.log('🎯 MASTER TRAINER PROFILE EDIT FIX TEST COMPLETE');
        
    } catch (error) {
        console.error('❌ Error during master trainer edit fix test:', error);
        await page.screenshot({ path: 'master-trainer-edit-fix-error.png', fullPage: true });
    } finally {
        await browser.close();
    }
}

testMasterTrainerEditFix();