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

async function testProfileDebug() {
    console.log('🔍 TESTING PROFILE SYSTEM COMPONENTS');
    console.log('================================================================================');
    
    const browser = await chromium.launch({ headless: false });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    try {
        // Login as admin to access WP admin
        console.log('📝 Logging in as admin...');
        await page.goto('https://upskill-staging.measurequick.com/wp-login.php');
        await page.fill('#user_login', 'joe@measurequick.com');
        await page.fill('#user_pass', 'VNL8TCd#o^L4');
        await page.click('#wp-submit');
        await page.waitForURL('**/wp-admin/**');
        console.log('✅ Admin login successful');
        
        // Check if trainer_profile post type exists
        console.log('🔍 Checking trainer_profile post type...');
        await page.goto('https://upskill-staging.measurequick.com/wp-admin/edit.php?post_type=trainer_profile');
        await page.waitForLoadState('networkidle');
        
        const postTypeTitle = await page.title();
        console.log(`📄 Post type page title: ${postTypeTitle}`);
        
        const profileCount = await page.locator('.wp-list-table tbody tr:not(.no-items)').count();
        console.log(`📊 Trainer profiles found: ${profileCount}`);
        
        if (profileCount > 0) {
            const firstProfile = await page.locator('.wp-list-table tbody tr:first-child .row-title').first();
            const profileTitle = await firstProfile.textContent();
            console.log(`👤 First profile: ${profileTitle}`);
            // Click to edit first profile
            await firstProfile.click();
            await page.waitForLoadState('networkidle');
            const editTitle = await page.title();
            console.log(`✏️ Edit profile title: ${editTitle}`);
            
            // Check meta fields
            const hasMetaFields = await page.locator('#postcustom').count() > 0;
            console.log(`📝 Has meta fields: ${hasMetaFields}`);
        }
        
        await page.screenshot({ path: 'admin-profile-debug.png', fullPage: true });
        
        // Now test as trainer
        console.log('🔄 Switching to trainer login...');
        await page.goto('https://upskill-staging.measurequick.com/wp-login.php?action=logout');
        await page.click('a[href*="logout"]').catch(() => {}); // Confirm logout if needed
        
        await page.goto('https://upskill-staging.measurequick.com/wp-login.php');
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'TestTrainer123!');
        await page.click('#wp-submit');
        await page.waitForURL('**/trainer/dashboard/**');
        console.log('✅ Trainer login successful');
        
        // Test profile page with error logging
        console.log('🔍 Testing profile page with console logging...');
        
        page.on('console', msg => console.log('🌐 Browser Console:', msg.text()));
        page.on('pageerror', err => console.log('❌ Page Error:', err.message));
        
        await page.goto('https://upskill-staging.measurequick.com/trainer/profile/');
        await page.waitForLoadState('networkidle');
        
        // Check for specific error messages or debug info
        const hasErrorMessages = await page.evaluate(() => {
            return {
                hasError: document.body.innerText.includes('Fatal error') || 
                         document.body.innerText.includes('Warning:') ||
                         document.body.innerText.includes('Notice:'),
                hasDebugInfo: document.body.innerText.includes('debug') ||
                             document.body.innerText.includes('Query Monitor'),
                pageContent: document.body.innerText.slice(0, 500)
            };
        });
        
        console.log('🔍 Error analysis:', hasErrorMessages);
        
        await page.screenshot({ path: 'trainer-profile-error-debug.png', fullPage: true });
        
        console.log('================================================================================');
        console.log('🎯 PROFILE DEBUG COMPLETE');
        
    } catch (error) {
        console.error('❌ Error during profile debug:', error);
        await page.screenshot({ path: 'profile-debug-error.png', fullPage: true });
    } finally {
        await browser.close();
    }
}

testProfileDebug();