/**
 * Test to get detailed error information from the edit page
 */

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

async function testErrorDetails() {
    console.log('🔍 Testing Error Details...\\n');
    
    const browser = await chromium.launch({
        headless: false,
        args: ['--disable-dev-shm-usage', '--no-sandbox']
    });
    
    const context = await browser.newContext({
        viewport: { width: 1280, height: 720 }
    });
    
    const page = await context.newPage();
    const baseUrl = 'https://upskill-staging.measurequick.com';
    
    try {
        // Step 1: Login first
        console.log('1️⃣ Logging in...');
        await page.goto(`${baseUrl}/training-login/`);
        await page.waitForLoadState('networkidle');
        
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        await page.press('input[name="pwd"]', 'Enter');
        
        // Wait for redirect
        await page.waitForURL('**/trainer/dashboard/**', { timeout: 10000 });
        console.log('✅ Login successful');
        
        // Step 2: Go to edit page and capture detailed error
        console.log('\\n2️⃣ Accessing edit page and capturing error details...');
        
        await page.goto(`${baseUrl}/trainer/event/edit/`);
        await page.waitForLoadState('networkidle');
        
        const errorDetails = await page.evaluate(() => {
            const title = document.title;
            const bodyContent = document.body.innerText;
            const htmlContent = document.body.innerHTML;
            
            // Look for specific error patterns
            const has404 = bodyContent.includes('404') || bodyContent.includes('not found') || 
                          bodyContent.includes('Not Found') || title.includes('404');
            
            const hasError = bodyContent.includes('error') || bodyContent.includes('Error') ||
                            title.includes('Error');
            
            const hasDebug = bodyContent.includes('PHP') || bodyContent.includes('Fatal') ||
                            bodyContent.includes('Warning') || bodyContent.includes('Notice');
            
            // Extract first 1000 characters of body content for analysis
            const bodySnippet = bodyContent.substring(0, 1000);
            
            // Look for specific WordPress error messages
            const hasTemplateError = bodyContent.includes('template') || bodyContent.includes('Template');
            const hasPermissionError = bodyContent.includes('permission') || bodyContent.includes('Permission');
            
            return {
                title,
                has404,
                hasError,
                hasDebug,
                hasTemplateError,
                hasPermissionError,
                bodySnippet,
                htmlSnippet: htmlContent.substring(0, 1500)
            };
        });
        
        console.log('   Page title:', errorDetails.title);
        console.log('   Has 404 error:', errorDetails.has404);
        console.log('   Has error message:', errorDetails.hasError);
        console.log('   Has PHP debug info:', errorDetails.hasDebug);
        console.log('   Has template error:', errorDetails.hasTemplateError);
        console.log('   Has permission error:', errorDetails.hasPermissionError);
        
        console.log('\\n   Body content snippet:');
        console.log('   ' + errorDetails.bodySnippet.replace(/\\n/g, '\\n   '));
        
        console.log('\\n   HTML content snippet:');
        console.log('   ' + errorDetails.htmlSnippet.replace(/\\n/g, '\\n   '));
        
        // Step 3: Test with event_id parameter
        console.log('\\n3️⃣ Testing with event_id parameter...');
        
        await page.goto(`${baseUrl}/trainer/event/edit/?event_id=6161`);
        await page.waitForLoadState('networkidle');
        
        const withParamDetails = await page.evaluate(() => {
            const title = document.title;
            const bodyContent = document.body.innerText;
            const hasCustomTemplate = bodyContent.includes('Custom Event Edit Template') ||
                                     document.body.innerHTML.includes('Custom Event Edit Template');
            
            return {
                title,
                bodySnippet: bodyContent.substring(0, 500),
                hasCustomTemplate
            };
        });
        
        console.log('   With event_id - Title:', withParamDetails.title);
        console.log('   With event_id - Has custom template:', withParamDetails.hasCustomTemplate);
        console.log('   With event_id - Body snippet:');
        console.log('   ' + withParamDetails.bodySnippet.replace(/\\n/g, '\\n   '));
        
        // Step 4: Check URL variations
        console.log('\\n4️⃣ Testing URL variations...');
        
        const urlVariations = [
            '/trainer/event/edit',
            '/trainer/event/edit/',
            '/trainer/event/edit/?event_id=123',
            '/trainer/events/edit/',
            '/trainer/edit-event/'
        ];
        
        for (const url of urlVariations) {
            await page.goto(`${baseUrl}${url}`);
            await page.waitForLoadState('networkidle', { timeout: 5000 });
            
            const result = await page.evaluate(() => ({
                title: document.title,
                url: window.location.href,
                hasError: document.title.includes('Error') || document.body.innerText.includes('404')
            }));
            
            console.log(`   ${url} -> ${result.hasError ? '❌' : '✅'} ${result.title}`);
        }
        
        // Take screenshot
        await page.screenshot({ 
            path: `error-details-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('\\n📸 Screenshot saved');
        
    } catch (error) {
        console.error('\\n❌ Test failed:', error.message);
        
        await page.screenshot({ 
            path: `error-test-failed-${Date.now()}.png`,
            fullPage: true 
        });
    } finally {
        console.log('\\n⏸️ Keeping browser open for inspection...');
        await page.waitForTimeout(10000);
        await browser.close();
    }
}

// Run test
testErrorDetails()
    .then(() => {
        console.log('\\n✨ Test completed!');
        process.exit(0);
    })
    .catch(error => {
        console.error('\\n💥 Test failed:', error);
        process.exit(1);
    });