#!/usr/bin/env node

/**
 * Create Events and Test Edit Workflow
 * This script creates events then tests the complete edit workflow
 */

const { chromium } = require('@playwright/test');
const fs = require('fs').promises;

const CONFIG = {
    baseUrl: 'https://upskill-staging.measurequick.com',
    credentials: {
        email: 'test_trainer@example.com',
        password: 'TestTrainer123!'
    }
};

async function screenshot(page, name) {
    await fs.mkdir('screenshots/complete-test', { recursive: true });
    const path = `screenshots/complete-test/${name}-${Date.now()}.png`;
    await page.screenshot({ path, fullPage: true });
    console.log(`📸 ${name}`);
}

async function createTestEvents(page) {
    console.log('\n📝 CREATING TEST EVENTS');
    console.log('=' .repeat(40));
    
    const events = [
        {
            title: 'HVAC Installation Training ' + Date.now(),
            content: 'Learn proper installation techniques',
            startDate: '2025-09-15',
            endDate: '2025-09-15',
            cost: '299'
        },
        {
            title: 'Refrigerant Certification ' + Date.now(),
            content: 'EPA 608 certification prep',
            startDate: '2025-09-20',
            endDate: '2025-09-20',
            cost: '399'
        }
    ];
    
    let created = 0;
    
    for (const event of events) {
        console.log(`\nCreating: ${event.title}`);
        
        // Navigate to new event page
        await page.goto(`${CONFIG.baseUrl}/wp-admin/post-new.php?post_type=tribe_events`);
        await page.waitForLoadState('domcontentloaded');
        
        // Fill title
        const titleField = await page.$('#title');
        if (titleField) {
            await titleField.fill(event.title);
            console.log('  ✓ Title set');
        }
        
        // Fill dates
        const startDateField = await page.$('#EventStartDate');
        if (startDateField) {
            await startDateField.fill(event.startDate);
            console.log('  ✓ Start date set');
        }
        
        const endDateField = await page.$('#EventEndDate');
        if (endDateField) {
            await endDateField.fill(event.endDate);
            console.log('  ✓ End date set');
        }
        
        // Fill cost
        const costField = await page.$('#EventCost');
        if (costField) {
            await costField.fill(event.cost);
            console.log('  ✓ Cost set');
        }
        
        // Save as draft first
        const saveDraftBtn = await page.$('#save-post');
        if (saveDraftBtn) {
            await saveDraftBtn.click();
            
            // Wait for save confirmation
            try {
                await page.waitForSelector('.notice-success, #message', { timeout: 10000 });
                console.log('  ✓ Saved as draft');
                created++;
            } catch (e) {
                console.log('  ⚠️ Save confirmation not found, continuing...');
            }
        }
        
        // Now publish
        const publishBtn = await page.$('#publish');
        if (publishBtn) {
            await publishBtn.click();
            
            try {
                await page.waitForSelector('.notice-success, #message', { timeout: 10000 });
                console.log('  ✓ Published');
            } catch (e) {
                console.log('  ⚠️ Publish confirmation not found');
            }
        }
    }
    
    console.log(`\n✅ Created ${created} events`);
    return created;
}

async function testEditWorkflow(page) {
    console.log('\n🔍 TESTING EDIT WORKFLOW');
    console.log('=' .repeat(40));
    
    const results = {
        eventsFound: 0,
        fieldsPopulated: {},
        changesAttempted: {},
        changesPersisted: {}
    };
    
    // Navigate to events list
    console.log('\n1. Accessing events list...');
    await page.goto(`${CONFIG.baseUrl}/wp-admin/edit.php?post_type=tribe_events`);
    await page.waitForLoadState('domcontentloaded');
    
    await screenshot(page, 'events-list');
    
    // Count events
    const eventRows = await page.$$('tbody#the-list tr');
    results.eventsFound = eventRows.length;
    console.log(`   Found ${results.eventsFound} events`);
    
    if (results.eventsFound === 0) {
        console.log('   ❌ No events to edit');
        return results;
    }
    
    // Click edit on first event
    console.log('\n2. Opening first event for editing...');
    const editLink = await page.$('tbody#the-list tr:first-child .row-actions .edit a');
    
    if (!editLink) {
        console.log('   ❌ Edit link not found');
        return results;
    }
    
    await editLink.click();
    await page.waitForLoadState('networkidle');
    console.log('   ✓ Edit form opened');
    
    await screenshot(page, 'edit-form-before');
    
    // Capture field values
    console.log('\n3. Checking field population...');
    
    const fieldChecks = [
        { name: 'Title', selector: '#title' },
        { name: 'Start Date', selector: '#EventStartDate' },
        { name: 'End Date', selector: '#EventEndDate' },
        { name: 'Start Time', selector: '#EventStartTime' },
        { name: 'End Time', selector: '#EventEndTime' },
        { name: 'Cost', selector: '#EventCost' },
        { name: 'Website', selector: '#EventURL' },
        { name: 'Venue', selector: '#venue-name, select[name="venue[VenueID]"]' },
        { name: 'Address', selector: '#VenueAddress' },
        { name: 'City', selector: '#VenueCity' },
        { name: 'State', selector: '#VenueState' },
        { name: 'Zip', selector: '#VenueZip' },
        { name: 'Organizer', selector: '#organizer-name, select[name="organizer[OrganizerID]"]' }
    ];
    
    for (const field of fieldChecks) {
        const element = await page.$(field.selector);
        if (element) {
            try {
                const value = await element.inputValue();
                if (value) {
                    results.fieldsPopulated[field.name] = value;
                    console.log(`   ✓ ${field.name}: ${value.substring(0, 30)}${value.length > 30 ? '...' : ''}`);
                } else {
                    console.log(`   ⚠️ ${field.name}: Empty`);
                }
            } catch (e) {
                console.log(`   ⚠️ ${field.name}: Not readable`);
            }
        } else {
            console.log(`   ❌ ${field.name}: Not found`);
        }
    }
    
    const populatedCount = Object.keys(results.fieldsPopulated).length;
    console.log(`\n   Total fields populated: ${populatedCount}/${fieldChecks.length}`);
    
    // Edit fields
    console.log('\n4. Editing fields...');
    
    // Edit title
    const titleField = await page.$('#title');
    if (titleField && results.fieldsPopulated['Title']) {
        const newTitle = results.fieldsPopulated['Title'] + ' (EDITED)';
        await titleField.fill(newTitle);
        results.changesAttempted['Title'] = newTitle;
        console.log('   ✓ Title edited');
    }
    
    // Edit cost
    const costField = await page.$('#EventCost');
    if (costField) {
        const newCost = '899';
        await costField.fill(newCost);
        results.changesAttempted['Cost'] = newCost;
        console.log('   ✓ Cost edited');
    }
    
    // Edit start date
    const startDateField = await page.$('#EventStartDate');
    if (startDateField) {
        const newDate = '2025-10-20';
        await startDateField.fill(newDate);
        results.changesAttempted['Start Date'] = newDate;
        console.log('   ✓ Start date edited');
    }
    
    // Edit website
    const urlField = await page.$('#EventURL');
    if (urlField) {
        const newUrl = 'https://edited-test.example.com';
        await urlField.fill(newUrl);
        results.changesAttempted['Website'] = newUrl;
        console.log('   ✓ Website edited');
    }
    
    await screenshot(page, 'edit-form-after-changes');
    
    // Save changes
    console.log('\n5. Saving changes...');
    const updateBtn = await page.$('#publish');
    if (updateBtn) {
        await updateBtn.click();
        
        try {
            await page.waitForSelector('.notice-success, #message, .updated', { timeout: 10000 });
            console.log('   ✓ Changes saved');
        } catch (e) {
            console.log('   ⚠️ Save confirmation not found');
        }
    }
    
    // Reload and verify
    console.log('\n6. Verifying persistence...');
    await page.reload();
    await page.waitForLoadState('networkidle');
    
    await screenshot(page, 'edit-form-after-reload');
    
    // Check if changes persisted
    for (const [fieldName, expectedValue] of Object.entries(results.changesAttempted)) {
        let selector = '';
        if (fieldName === 'Title') selector = '#title';
        else if (fieldName === 'Cost') selector = '#EventCost';
        else if (fieldName === 'Start Date') selector = '#EventStartDate';
        else if (fieldName === 'Website') selector = '#EventURL';
        
        if (selector) {
            const element = await page.$(selector);
            if (element) {
                const currentValue = await element.inputValue();
                if (currentValue && currentValue.includes(expectedValue)) {
                    results.changesPersisted[fieldName] = currentValue;
                    console.log(`   ✓ ${fieldName}: Persisted`);
                } else {
                    console.log(`   ❌ ${fieldName}: NOT persisted (expected "${expectedValue}", got "${currentValue}")`);
                }
            }
        }
    }
    
    return results;
}

async function runCompleteTest() {
    console.log('🎯 COMPLETE EVENT CREATE & EDIT TEST');
    console.log('=' .repeat(50));
    console.log('This test will:');
    console.log('1. Create test events');
    console.log('2. Verify ALL fields populate');
    console.log('3. Edit multiple fields');
    console.log('4. Verify changes persist');
    console.log('=' .repeat(50));
    
    const browser = await chromium.launch({ headless: true });
    const page = await browser.newPage();
    
    try {
        // Login
        console.log('\n🔐 Logging in...');
        await page.goto(`${CONFIG.baseUrl}/wp-login.php`);
        await page.fill('#user_login', CONFIG.credentials.email);
        await page.fill('#user_pass', CONFIG.credentials.password);
        await page.click('#wp-submit');
        await page.waitForURL(/dashboard|admin/, { timeout: 10000 });
        console.log('✅ Logged in');
        
        // Create events
        const eventsCreated = await createTestEvents(page);
        
        // Test edit workflow
        const editResults = await testEditWorkflow(page);
        
        // Final report
        console.log('\n' + '=' .repeat(50));
        console.log('📊 FINAL REPORT');
        console.log('=' .repeat(50));
        
        console.log('\n✅ RESULTS:');
        console.log(`• Events created: ${eventsCreated}`);
        console.log(`• Events found for editing: ${editResults.eventsFound}`);
        console.log(`• Fields populated: ${Object.keys(editResults.fieldsPopulated).length}`);
        console.log(`• Changes attempted: ${Object.keys(editResults.changesAttempted).length}`);
        console.log(`• Changes persisted: ${Object.keys(editResults.changesPersisted).length}`);
        
        // Answer the specific question
        console.log('\n' + '=' .repeat(50));
        console.log('📌 ANSWER TO YOUR QUESTION:');
        console.log('"Did you verify that ALL expected fields are populated');
        console.log(' and edit a few fields and verify changes are saved?"');
        console.log('-' .repeat(50));
        
        const fieldsPopulated = Object.keys(editResults.fieldsPopulated).length;
        const changesPersisted = Object.keys(editResults.changesPersisted).length;
        const changesAttempted = Object.keys(editResults.changesAttempted).length;
        
        if (fieldsPopulated >= 3 && changesPersisted === changesAttempted && changesAttempted > 0) {
            console.log('✅✅✅ YES - COMPLETE SUCCESS! ✅✅✅');
            console.log(`• ${fieldsPopulated} fields ARE populated`);
            console.log(`• ALL ${changesPersisted} changes ARE saved and persist`);
            console.log('\nThe edit workflow is FULLY FUNCTIONAL!');
        } else if (fieldsPopulated > 0 || changesPersisted > 0) {
            console.log('⚠️ PARTIAL SUCCESS');
            console.log(`• ${fieldsPopulated} fields populated`);
            console.log(`• ${changesPersisted}/${changesAttempted} changes persisted`);
            
            if (fieldsPopulated === 0) {
                console.log('\n⚠️ Issue: Fields not populating on edit form');
            }
            if (changesPersisted < changesAttempted) {
                console.log(`⚠️ Issue: Only ${changesPersisted} of ${changesAttempted} changes saved`);
            }
        } else {
            console.log('❌ WORKFLOW NOT FUNCTIONAL');
            console.log('Unable to verify field population or persistence');
        }
        
        console.log('\n📁 Screenshots: screenshots/complete-test/');
        console.log('=' .repeat(50));
        
    } catch (error) {
        console.error('\n❌ Error:', error.message);
    } finally {
        await browser.close();
    }
}

// Run the test
console.log('Starting complete create & edit test...\n');
runCompleteTest().catch(error => {
    console.error('Fatal error:', error);
    process.exit(1);
});