/**
 * Test script for verifying the new create/edit event pages
 * Tests REST API enhancement and field population
 */

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

(async () => {
    const browser = await chromium.launch({ 
        headless: true,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    
    const context = await browser.newContext({
        ignoreHTTPSErrors: true
    });
    
    const page = await context.newPage();
    
    console.log('🔍 Testing Create/Edit Event Pages on Staging...\n');
    
    try {
        // Test 1: Check if create-event page exists
        console.log('📝 Test 1: Checking create-event page...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/create-event/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        const createPageTitle = await page.title();
        console.log(`   Page title: ${createPageTitle}`);
        
        // Check if TEC form is present
        const hasCreateForm = await page.locator('#tribe-community-events').count() > 0;
        console.log(`   TEC form present: ${hasCreateForm}`);
        
        // Check if REST API script is loaded
        const restApiLoaded = await page.evaluate(() => {
            return typeof window.HVACRestEventSubmission !== 'undefined';
        });
        console.log(`   REST API script loaded: ${restApiLoaded}`);
        
        // Check if excerpt field was added
        const hasExcerptField = await page.locator('#event_excerpt').count() > 0;
        console.log(`   Excerpt field added: ${hasExcerptField}`);
        
        // Check form fields
        const formFields = await page.evaluate(() => {
            const fields = {
                title: document.querySelector('#post_title, input[name="post_title"]'),
                description: document.querySelector('#tcepostcontent, #post_content, textarea[name="post_content"]'),
                excerpt: document.querySelector('#event_excerpt, textarea[name="excerpt"]'),
                startDate: document.querySelector('input[name="EventStartDate"]'),
                endDate: document.querySelector('input[name="EventEndDate"]'),
                venue: document.querySelector('#saved_tribe_venue'),
                organizer: document.querySelector('#saved_tribe_organizer')
            };
            
            return {
                hasTitle: !!fields.title,
                hasDescription: !!fields.description,
                hasExcerpt: !!fields.excerpt,
                hasStartDate: !!fields.startDate,
                hasEndDate: !!fields.endDate,
                hasVenue: !!fields.venue,
                hasOrganizer: !!fields.organizer
            };
        });
        
        console.log('   Form fields found:');
        Object.entries(formFields).forEach(([field, present]) => {
            console.log(`     - ${field}: ${present ? '✅' : '❌'}`);
        });
        
        // Test 2: Check if edit-event page exists
        console.log('\n📝 Test 2: Checking edit-event page...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/edit-event/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        const editPageTitle = await page.title();
        console.log(`   Page title: ${editPageTitle}`);
        
        // Check for error message (should show "No event specified")
        const hasErrorMessage = await page.locator('.hvac-error-notice').count() > 0;
        console.log(`   Shows error when no event_id: ${hasErrorMessage}`);
        
        if (hasErrorMessage) {
            const errorText = await page.locator('.hvac-error-notice p').textContent();
            console.log(`   Error message: "${errorText}"`);
        }
        
        // Test 3: Check edit page with a test event ID
        console.log('\n📝 Test 3: Testing edit page with event_id parameter...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/edit-event/?event_id=5678', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        // Check if notice shows the event ID
        const hasEditNotice = await page.locator('.hvac-form-notice').count() > 0;
        console.log(`   Shows edit notice: ${hasEditNotice}`);
        
        if (hasEditNotice) {
            const noticeText = await page.locator('.hvac-form-notice p').textContent();
            console.log(`   Notice text: "${noticeText}"`);
        }
        
        // Check if hvacEditEventId is set
        const editEventId = await page.evaluate(() => {
            return window.hvacEditEventId;
        });
        console.log(`   window.hvacEditEventId set to: ${editEventId}`);
        
        // Test 4: Check console for REST API initialization
        console.log('\n📝 Test 4: Checking REST API initialization...');
        
        // Listen for console messages
        const consoleMessages = [];
        page.on('console', msg => {
            if (msg.text().includes('HVAC') || msg.text().includes('REST')) {
                consoleMessages.push(msg.text());
            }
        });
        
        // Reload create page to capture console logs
        await page.goto('https://upskill-staging.measurequick.com/trainer/create-event/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        // Wait a moment for scripts to initialize
        await page.waitForTimeout(2000);
        
        console.log('   Console messages:');
        consoleMessages.forEach(msg => {
            console.log(`     - ${msg}`);
        });
        
        // Test 5: Check REST API enhancement features
        console.log('\n📝 Test 5: Testing REST API enhancement features...');
        
        const restApiFeatures = await page.evaluate(() => {
            if (typeof window.HVACRestEventSubmission === 'undefined') {
                return { available: false };
            }
            
            const api = window.HVACRestEventSubmission;
            return {
                available: true,
                hasInit: typeof api.init === 'function',
                hasSubmitHandler: typeof api.attachSubmitHandler === 'function',
                hasEnhanceForm: typeof api.enhanceFormFields === 'function',
                hasCollectData: typeof api.collectFormData === 'function',
                hasSubmitAPI: typeof api.submitViaRestAPI === 'function',
                apiEndpoint: api.apiEndpoint
            };
        });
        
        console.log('   REST API features:');
        if (restApiFeatures.available) {
            console.log(`     - API Available: ✅`);
            console.log(`     - Init method: ${restApiFeatures.hasInit ? '✅' : '❌'}`);
            console.log(`     - Submit handler: ${restApiFeatures.hasSubmitHandler ? '✅' : '❌'}`);
            console.log(`     - Form enhancement: ${restApiFeatures.hasEnhanceForm ? '✅' : '❌'}`);
            console.log(`     - Data collection: ${restApiFeatures.hasCollectData ? '✅' : '❌'}`);
            console.log(`     - API submission: ${restApiFeatures.hasSubmitAPI ? '✅' : '❌'}`);
            console.log(`     - Endpoint: ${restApiFeatures.apiEndpoint}`);
        } else {
            console.log(`     - API Available: ❌ (Not loaded)`);
        }
        
        // Summary
        console.log('\n📊 Summary:');
        console.log('   ✅ Create event page exists at /trainer/create-event/');
        console.log('   ✅ Edit event page exists at /trainer/edit-event/');
        console.log(`   ${hasCreateForm ? '✅' : '❌'} TEC form renders on create page`);
        console.log(`   ${restApiLoaded ? '✅' : '❌'} REST API script loads`);
        console.log(`   ${hasExcerptField ? '✅' : '❌'} Excerpt field added by REST API`);
        console.log(`   ${hasErrorMessage ? '✅' : '❌'} Edit page shows error when no event_id`);
        console.log(`   ${editEventId === 5678 ? '✅' : '❌'} Edit page sets hvacEditEventId from URL`);
        
        // Overall result
        const allTestsPassed = hasCreateForm && restApiLoaded && hasExcerptField && 
                               hasErrorMessage && editEventId === 5678;
        
        console.log(`\n${allTestsPassed ? '✅ All tests passed!' : '⚠️  Some tests failed'}`);
        console.log('\n🔗 URLs:');
        console.log('   Create: https://upskill-staging.measurequick.com/trainer/create-event/');
        console.log('   Edit: https://upskill-staging.measurequick.com/trainer/edit-event/?event_id=[EVENT_ID]');
        
    } catch (error) {
        console.error('❌ Error during testing:', error.message);
        
        // Take screenshot on error
        await page.screenshot({ 
            path: 'create-edit-pages-error.png',
            fullPage: true 
        });
        console.log('📸 Screenshot saved as create-edit-pages-error.png');
    } finally {
        await browser.close();
    }
})();