/**
 * Test REST API Proof of Concept
 * 
 * Tests the HVAC REST API Event Submission System to verify:
 * 1. REST API endpoints are accessible
 * 2. Authentication works properly
 * 3. All fields including excerpt can be submitted
 * 4. Events are created successfully with 100% field control
 */

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

async function testRestApiPoc() {
    console.log('🧪 Testing REST API Proof of Concept...');
    console.log('='.repeat(60));
    
    const browser = await chromium.launch({ 
        headless: true, // Run in headless mode
        slowMo: 500
    });
    
    try {
        const context = await browser.newContext({
            viewport: { width: 1400, height: 900 }
        });
        
        const page = await context.newPage();
        
        // Enable console logging
        page.on('console', msg => {
            const text = msg.text();
            if (text.includes('[HVAC REST]')) {
                console.log(`🔧 ${text}`);
            } else if (msg.type() === 'error') {
                console.log(`❌ Console Error: ${text}`);
            }
        });
        
        // Step 1: Login as trainer
        console.log('\n📝 Step 1: Logging in as trainer...');
        await page.goto('https://upskill-staging.measurequick.com/training-login/');
        await page.waitForTimeout(2000);
        
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'TestTrainer123!');
        await page.click('#wp-submit');
        await page.waitForTimeout(3000);
        
        const afterLoginUrl = page.url();
        console.log(`✅ Logged in - redirected to: ${afterLoginUrl}`);
        
        // Step 2: Navigate to event creation page
        console.log('\n📝 Step 2: Navigating to event creation page...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/');
        await page.waitForTimeout(3000);
        
        // Step 3: Check if REST API script is loaded
        console.log('\n📝 Step 3: Checking REST API script loading...');
        
        const restApiScriptLoaded = await page.evaluate(() => {
            return typeof HVACRestEventSubmission !== 'undefined';
        });
        
        if (restApiScriptLoaded) {
            console.log('✅ REST API script is loaded');
        } else {
            console.log('❌ REST API script NOT loaded - injecting manually...');
            
            // Inject the REST API script manually for testing
            await page.addScriptTag({
                path: '/home/ben/dev/upskill-event-manager/assets/js/hvac-rest-api-event-submission.js'
            });
            
            // Wait for script to initialize
            await page.waitForTimeout(1000);
            
            // Initialize manually
            await page.evaluate(() => {
                if (typeof HVACRestEventSubmission !== 'undefined') {
                    HVACRestEventSubmission.init();
                    console.log('[HVAC REST] Manually initialized');
                }
            });
        }
        
        // Step 4: Check if TEC form exists
        console.log('\n📝 Step 4: Checking for TEC form...');
        
        const formExists = await page.evaluate(() => {
            const formSelectors = [
                '#tribe-community-events form',
                '#tribe-community-events-form',
                '.tribe-community-events form',
                'form[name="community-event"]'
            ];
            
            for (const selector of formSelectors) {
                const form = document.querySelector(selector);
                if (form) {
                    console.log(`[HVAC REST] Found form: ${selector}`);
                    return true;
                }
            }
            return false;
        });
        
        if (!formExists) {
            console.log('❌ No TEC form found on page');
            
            // Check what's actually on the page
            const pageContent = await page.evaluate(() => {
                const body = document.body;
                return {
                    hasShortcode: body.innerHTML.includes('[tribe_community_events'),
                    hasTribeDiv: !!document.querySelector('#tribe-community-events'),
                    bodyClasses: body.className,
                    mainContent: document.querySelector('.entry-content')?.innerHTML.substring(0, 500)
                };
            });
            
            console.log('📋 Page analysis:');
            console.log(`   Has shortcode: ${pageContent.hasShortcode}`);
            console.log(`   Has tribe div: ${pageContent.hasTribeDiv}`);
            console.log(`   Body classes: ${pageContent.bodyClasses}`);
            
            // Take screenshot for debugging
            await page.screenshot({ 
                path: '/home/ben/dev/upskill-event-manager/test-results/rest-api-no-form.png',
                fullPage: true 
            });
            
            return {
                success: false,
                error: 'TEC form not found on page'
            };
        }
        
        console.log('✅ TEC form found');
        
        // Step 5: Check if excerpt field was added by REST API script
        console.log('\n📝 Step 5: Checking for enhanced excerpt field...');
        
        const excerptFieldAdded = await page.evaluate(() => {
            const excerptField = document.querySelector('#event_excerpt');
            if (excerptField) {
                console.log('[HVAC REST] Excerpt field found');
                return true;
            }
            return false;
        });
        
        if (excerptFieldAdded) {
            console.log('✅ Excerpt field successfully added by REST API script');
        } else {
            console.log('⚠️ Excerpt field not added - attempting to add manually...');
            
            await page.evaluate(() => {
                if (typeof HVACRestEventSubmission !== 'undefined') {
                    HVACRestEventSubmission.enhanceFormFields();
                }
            });
            
            await page.waitForTimeout(1000);
        }
        
        // Step 6: Fill out the form with test data
        console.log('\n📝 Step 6: Filling out event form with test data...');
        
        const testEventData = {
            title: `REST API Test Event ${Date.now()}`,
            description: 'This is a test event created via REST API to verify 100% field control including excerpt field.',
            excerpt: 'This excerpt field is NOT supported by TEC frontend but works via REST API!',
            startDate: '12/25/2024',
            startTime: '10:00 am',
            endDate: '12/25/2024',
            endTime: '5:00 pm',
            venue: 'Test Venue Houston',
            address: '123 Test St',
            city: 'Houston',
            state: 'TX',
            zip: '77001',
            cost: '199'
        };
        
        // Fill basic fields
        await page.fill('input[name="post_title"]', testEventData.title);
        console.log('✅ Filled title');
        
        // Fill description (handle TinyMCE or textarea)
        const hasWysiwyg = await page.evaluate(() => {
            return typeof tinymce !== 'undefined' && tinymce.get('tcepostcontent');
        });
        
        if (hasWysiwyg) {
            await page.evaluate((desc) => {
                tinymce.get('tcepostcontent').setContent(desc);
            }, testEventData.description);
            console.log('✅ Filled description (TinyMCE)');
        } else {
            await page.fill('textarea[name="post_content"]', testEventData.description);
            console.log('✅ Filled description (textarea)');
        }
        
        // Fill excerpt if field exists
        const excerptField = await page.$('#event_excerpt');
        if (excerptField) {
            await excerptField.fill(testEventData.excerpt);
            console.log('✅ Filled excerpt field');
        } else {
            console.log('⚠️ Excerpt field not available');
        }
        
        // Fill date/time fields
        await page.fill('input[name="EventStartDate"]', testEventData.startDate);
        await page.fill('input[name="EventStartTime"]', testEventData.startTime);
        await page.fill('input[name="EventEndDate"]', testEventData.endDate);
        await page.fill('input[name="EventEndTime"]', testEventData.endTime);
        console.log('✅ Filled date/time fields');
        
        // Fill venue fields
        await page.fill('input[name="venue[Venue]"]', testEventData.venue);
        await page.fill('input[name="venue[Address]"]', testEventData.address);
        await page.fill('input[name="venue[City]"]', testEventData.city);
        await page.fill('#StateProvinceText', testEventData.state);
        await page.fill('#EventZip', testEventData.zip);
        console.log('✅ Filled venue fields');
        
        // Fill cost
        await page.fill('input[name="EventCost"]', testEventData.cost);
        console.log('✅ Filled cost field');
        
        // Take screenshot before submission
        await page.screenshot({ 
            path: '/home/ben/dev/upskill-event-manager/test-results/rest-api-form-filled.png',
            fullPage: true 
        });
        console.log('📸 Screenshot saved: form filled');
        
        // Step 7: Test REST API interception
        console.log('\n📝 Step 7: Testing REST API form submission interception...');
        
        // Set up request interception to monitor REST API calls
        const apiRequests = [];
        page.on('request', request => {
            if (request.url().includes('/wp-json/tribe/events/')) {
                apiRequests.push({
                    url: request.url(),
                    method: request.method(),
                    headers: request.headers(),
                    postData: request.postData()
                });
                console.log(`🔄 REST API Request: ${request.method()} ${request.url()}`);
            }
        });
        
        page.on('response', response => {
            if (response.url().includes('/wp-json/tribe/events/')) {
                console.log(`📥 REST API Response: ${response.status()} ${response.url()}`);
            }
        });
        
        // Submit the form
        console.log('\n📝 Step 8: Submitting form...');
        
        // Find and click submit button
        const submitButton = await page.$('button[type="submit"], input[type="submit"]');
        if (submitButton) {
            console.log('🎯 Clicking submit button...');
            await submitButton.click();
            
            // Wait for submission
            await page.waitForTimeout(5000);
            
            // Check if REST API was called
            if (apiRequests.length > 0) {
                console.log(`✅ REST API called ${apiRequests.length} time(s)`);
                
                apiRequests.forEach((req, index) => {
                    console.log(`\n📋 API Request ${index + 1}:`);
                    console.log(`   URL: ${req.url}`);
                    console.log(`   Method: ${req.method}`);
                    if (req.postData) {
                        console.log(`   Has POST data: Yes`);
                        // Check if excerpt is in the data
                        if (req.postData.includes('excerpt')) {
                            console.log(`   ✅ Excerpt field included in request!`);
                        }
                    }
                });
            } else {
                console.log('⚠️ No REST API calls detected');
                console.log('   Form may have submitted via standard method');
            }
            
            // Check for success message
            const successMessage = await page.$('.tribe-events-notices-success');
            if (successMessage) {
                const messageText = await successMessage.textContent();
                console.log(`✅ Success message: ${messageText}`);
            }
            
            // Check current URL for redirect
            const afterSubmitUrl = page.url();
            console.log(`📍 After submit URL: ${afterSubmitUrl}`);
            
            if (afterSubmitUrl !== page.url()) {
                console.log('✅ Page redirected after submission');
            }
            
        } else {
            console.log('❌ Submit button not found');
        }
        
        // Take final screenshot
        await page.screenshot({ 
            path: '/home/ben/dev/upskill-event-manager/test-results/rest-api-after-submit.png',
            fullPage: true 
        });
        console.log('📸 Screenshot saved: after submission');
        
        // Final summary
        console.log('\n' + '='.repeat(60));
        console.log('📊 REST API POC Test Summary:');
        console.log('='.repeat(60));
        console.log(`✅ Login successful: Yes`);
        console.log(`✅ REST API script loaded: ${restApiScriptLoaded ? 'Yes' : 'Manually injected'}`);
        console.log(`✅ TEC form found: ${formExists ? 'Yes' : 'No'}`);
        console.log(`✅ Excerpt field added: ${excerptFieldAdded ? 'Yes' : 'No'}`);
        console.log(`✅ REST API calls made: ${apiRequests.length > 0 ? 'Yes' : 'No'}`);
        
        if (apiRequests.length > 0) {
            console.log('\n🎉 REST API SOLUTION WORKS!');
            console.log('✅ Can intercept form submission');
            console.log('✅ Can add excerpt field to form');
            console.log('✅ Can submit via REST API with all fields');
            console.log('\n💡 Ready to create separate pages for create/edit');
        } else {
            console.log('\n⚠️ REST API interception needs debugging');
            console.log('💡 Check if form submission handler is properly attached');
        }
        
        return {
            success: apiRequests.length > 0,
            restApiCalled: apiRequests.length > 0,
            excerptFieldAdded: excerptFieldAdded
        };
        
    } catch (error) {
        console.error('❌ Test failed:', error);
        
        // Take error screenshot if page exists
        if (typeof page !== 'undefined') {
            await page.screenshot({ 
                path: '/home/ben/dev/upskill-event-manager/test-results/rest-api-error.png',
                fullPage: true 
            });
        }
        
        return { success: false, error: error.message };
    } finally {
        console.log('\n⏸️ Closing browser...');
        await browser.close();
    }
}

// Run the test
if (require.main === module) {
    testRestApiPoc()
        .then(result => {
            console.log('\n🏁 REST API POC Test Complete');
            process.exit(result.success ? 0 : 1);
        })
        .catch(error => {
            console.error('❌ Test runner failed:', error);
            process.exit(1);
        });
}

module.exports = { testRestApiPoc };