/**
 * Final verification test for the original target URL
 */

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

async function testFinalVerification() {
    console.log('🔍 Final Verification Test...\\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 with proper handling
        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 to dashboard
        await page.waitForURL('**/trainer/dashboard/**', { timeout: 10000 });
        console.log('✅ Login successful');
        
        // Step 2: Test the original failing URL
        console.log('\\n2️⃣ Testing original target URL...');
        const targetUrl = `${baseUrl}/trainer/event/edit/?event_id=6161`;
        console.log('   Target URL:', targetUrl);
        
        await page.goto(targetUrl);
        await page.waitForLoadState('networkidle');
        
        const result = await page.evaluate(() => {
            const currentUrl = window.location.href;
            const title = document.title;
            const hasLoginForm = document.querySelector('input[name="log"]') !== null;
            const hasError = title.includes('Error') || document.body.innerText.includes('permission');
            const hasEventForm = document.querySelector('.hvac-event-form, input[name="post_title"]') !== null;
            const hasCustomTemplate = document.body.innerHTML.includes('Custom Event Edit Template');
            
            // Get form fields for verification
            const titleField = document.querySelector('input[name="post_title"]');
            const descriptionField = document.querySelector('textarea[name="post_content"]');
            const startDateField = document.querySelector('input[name="EventStartDate"]');
            
            return {
                currentUrl,
                title,
                hasLoginForm,
                hasError,
                hasEventForm,
                hasCustomTemplate,
                hasFormFields: !!(titleField && descriptionField && startDateField),
                bodySnippet: document.body.innerText.substring(0, 500)
            };
        });
        
        console.log('   Final URL:', result.currentUrl);
        console.log('   Page title:', result.title);
        console.log('   Redirected to login:', result.hasLoginForm);
        console.log('   Has error:', result.hasError);
        console.log('   Has event form:', result.hasEventForm);
        console.log('   Has custom template marker:', result.hasCustomTemplate);
        console.log('   Has form fields (title, description, date):', result.hasFormFields);
        
        if (result.hasLoginForm) {
            console.log('\\n❌ FAILED - Still redirected to login');
        } else if (result.hasError) {
            console.log('\\n❌ FAILED - Permission or other error');
            console.log('   Error content:', result.bodySnippet);
        } else if (result.hasFormFields) {
            console.log('\\n✅ SUCCESS - Custom event edit form is working!');
        } else {
            console.log('\\n⚠️ PARTIAL - Page loads but form may not be complete');
            console.log('   Content preview:', result.bodySnippet);
        }
        
        // Step 3: Test without event_id (new event)
        console.log('\\n3️⃣ Testing new event creation (no event_id)...');
        
        await page.goto(`${baseUrl}/trainer/event/edit/`);
        await page.waitForLoadState('networkidle');
        
        const newEventResult = await page.evaluate(() => {
            const title = document.title;
            const hasError = title.includes('Error');
            const hasEventForm = document.querySelector('input[name="post_title"]') !== null;
            const bodySnippet = document.body.innerText.substring(0, 300);
            
            return { title, hasError, hasEventForm, bodySnippet };
        });
        
        console.log('   Title:', newEventResult.title);
        console.log('   Has error:', newEventResult.hasError);
        console.log('   Has event form:', newEventResult.hasEventForm);
        
        if (newEventResult.hasError) {
            console.log('   ❌ New event creation failed');
        } else if (newEventResult.hasEventForm) {
            console.log('   ✅ New event creation works');
        } else {
            console.log('   ⚠️ New event - unclear result');
        }
        
        // Take final screenshot
        await page.screenshot({ 
            path: `final-verification-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('\\n📸 Screenshot saved');
        
        // Summary
        console.log('\\n📋 FINAL SUMMARY:');
        if (!result.hasLoginForm && !result.hasError && result.hasFormFields) {
            console.log('🎉 SUCCESS: Custom event edit template is working correctly!');
            console.log('   - Authentication works');
            console.log('   - Page loads without errors');
            console.log('   - Custom form fields are present');
            console.log('   - Template loading is working');
        } else {
            console.log('❌ Issues remain:');
            if (result.hasLoginForm) console.log('   - Still redirected to login');
            if (result.hasError) console.log('   - Permission or template errors');
            if (!result.hasFormFields) console.log('   - Form fields missing');
        }
        
    } catch (error) {
        console.error('\\n❌ Test failed:', error.message);
        
        await page.screenshot({ 
            path: `error-final-verification-${Date.now()}.png`,
            fullPage: true 
        });
    } finally {
        console.log('\\n⏸️ Keeping browser open for inspection...');
        await page.waitForTimeout(10000);
        await browser.close();
    }
}

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