#!/usr/bin/env node

/**
 * WP-Admin Event Seeder Test  
 * Uses standard WordPress login with admin account
 */

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

// Configure XWayland display
process.env.DISPLAY = ':0';
try {
    const xauthFile = execSync('ls /run/user/1000/.mutter-Xwaylandauth.* 2>/dev/null | head -n1', { encoding: 'utf8' }).trim();
    if (xauthFile) {
        process.env.XAUTHORITY = xauthFile;
    }
} catch (e) {
    // Continue without XAUTHORITY
}

const CONFIG = {
    baseUrl: 'https://upskill-staging.measurequick.com',
    credentials: {
        // Admin account
        email: 'ben@upskillhvac.com',
        password: 'Stage123!'
    }
};

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

async function runWPAdminSeederTest() {
    console.log('🌱 WP-ADMIN EVENT SEEDER TEST');
    console.log('=' .repeat(60));
    console.log('Using standard WordPress login');
    console.log('=' .repeat(60));
    
    const browser = await chromium.launch({ 
        headless: false,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    
    const page = await browser.newPage();
    
    try {
        // 1. LOGIN via standard WP login
        console.log('\n📝 STEP 1: Login via /wp-login.php');
        await page.goto(`${CONFIG.baseUrl}/wp-login.php`);
        await page.waitForLoadState('domcontentloaded');
        
        // Fill WordPress login form
        await page.fill('#user_login', CONFIG.credentials.email);
        await page.fill('#user_pass', CONFIG.credentials.password);
        console.log('✅ Filled login credentials');
        
        await screenshot(page, '01-login-form');
        
        // Submit login
        await page.click('#wp-submit');
        
        // Wait for successful login
        try {
            await page.waitForURL('**/wp-admin/**', { timeout: 10000 });
            console.log('✅ Logged in successfully!');
        } catch (e) {
            console.log('⚠️ Login redirect timeout, checking current URL...');
            const currentUrl = page.url();
            if (currentUrl.includes('wp-admin')) {
                console.log('✅ Actually logged in successfully');
            } else {
                console.log(`❌ Login failed, current URL: ${currentUrl}`);
            }
        }
        
        await screenshot(page, '02-after-login');
        
        // 2. ACCESS SEEDER PAGE
        console.log('\n📝 STEP 2: Access Event Seeder Page');
        await page.goto(`${CONFIG.baseUrl}/wp-admin/admin.php?page=hvac-seed-events`);
        await page.waitForLoadState('networkidle');
        await screenshot(page, '03-seeder-page');
        
        // Check page content
        const pageContent = await page.locator('body').textContent();
        
        if (pageContent.includes('HVAC Event Seeder') || pageContent.includes('Create Test Events')) {
            console.log('✅ Successfully accessed seeder page!');
            
            // Check for existing events
            const eventsMatch = pageContent.match(/Found\s+<strong>(\d+)<\/strong>\s+events/);
            if (eventsMatch) {
                const existingCount = parseInt(eventsMatch[1]);
                console.log(`\n📊 Current Status: ${existingCount} events in database`);
                
                if (existingCount === 0) {
                    // CREATE EVENTS
                    console.log('\n📝 STEP 3: Creating Test Events');
                    
                    const seedButton = await page.locator('a.button-primary:has-text("Create Test Events")');
                    if (await seedButton.isVisible()) {
                        console.log('Clicking seed button...');
                        await seedButton.click();
                        
                        await page.waitForLoadState('networkidle');
                        await page.waitForTimeout(2000);
                        await screenshot(page, '04-after-seed');
                        
                        const successMessage = await page.locator('.notice-success').textContent().catch(() => '');
                        if (successMessage) {
                            console.log('✅ Events seeded successfully!');
                            const countMatch = successMessage.match(/(\d+)/);
                            if (countMatch) {
                                console.log(`  Created ${countMatch[1]} events`);
                            }
                        }
                    }
                }
            }
            
            // 3. VERIFY EVENTS IN LIST
            console.log('\n📝 STEP 3: Verify Events in Admin List');
            await page.goto(`${CONFIG.baseUrl}/wp-admin/edit.php?post_type=tribe_events`);
            await page.waitForLoadState('networkidle');
            await screenshot(page, '05-events-list');
            
            const eventRows = await page.$$('tbody#the-list tr');
            console.log(`\n✅ Found ${eventRows.length} events in admin list`);
            
            if (eventRows.length > 0) {
                // List events
                console.log('\nEvent titles:');
                for (let i = 0; i < Math.min(3, eventRows.length); i++) {
                    const title = await eventRows[i].$eval('.row-title', el => el.textContent).catch(() => 'Unknown');
                    console.log(`  ${i+1}. ${title}`);
                }
                
                // 4. TEST EDIT WORKFLOW
                console.log('\n📝 STEP 4: Testing Edit Workflow');
                console.log('=' .repeat(40));
                
                // Click edit on first event
                const editLink = await page.$('tbody#the-list tr:first-child .row-actions .edit a');
                if (editLink) {
                    await editLink.click();
                    await page.waitForLoadState('networkidle');
                    console.log('✅ Opened event for editing');
                    await screenshot(page, '06-edit-form');
                    
                    // Check ALL fields - comprehensive list
                    console.log('\n📊 CHECKING ALL EVENT FIELDS:');
                    console.log('-' .repeat(40));
                    
                    const allFields = {
                        // Basic Info
                        'Title': await page.$eval('#title', el => el.value).catch(() => ''),
                        'Content': await page.$eval('#content', el => el.value).catch(() => ''),
                        
                        // Date & Time
                        'Start Date': await page.$eval('#EventStartDate', el => el.value).catch(() => ''),
                        'End Date': await page.$eval('#EventEndDate', el => el.value).catch(() => ''),
                        'Start Time': await page.$eval('#EventStartTime', el => el.value).catch(() => ''),
                        'End Time': await page.$eval('#EventEndTime', el => el.value).catch(() => ''),
                        'All Day': await page.$eval('#EventAllDay', el => el.checked).catch(() => false),
                        
                        // Cost
                        'Cost': await page.$eval('#EventCost', el => el.value).catch(() => ''),
                        'Currency Symbol': await page.$eval('#EventCurrencySymbol', el => el.value).catch(() => ''),
                        
                        // Event Details
                        'Website URL': await page.$eval('#EventURL', el => el.value).catch(() => ''),
                        'Show Map': await page.$eval('#EventShowMap', el => el.checked).catch(() => false),
                        'Show Map Link': await page.$eval('#EventShowMapLink', el => el.checked).catch(() => false),
                        
                        // Venue (if linked)
                        'Venue ID': await page.$eval('#EventVenueID', el => el.value).catch(() => ''),
                        
                        // Organizer (if linked)
                        'Organizer ID': await page.$eval('#EventOrganizerID', el => el.value).catch(() => '')
                    };
                    
                    let populatedCount = 0;
                    let emptyFields = [];
                    
                    for (const [name, value] of Object.entries(allFields)) {
                        if (value && value !== '' && value !== false) {
                            console.log(`  ✅ ${name}: ${String(value).substring(0, 50)}`);
                            populatedCount++;
                        } else {
                            console.log(`  ❌ ${name}: EMPTY`);
                            emptyFields.push(name);
                        }
                    }
                    
                    console.log('-' .repeat(40));
                    console.log(`TOTAL: ${populatedCount}/${Object.keys(allFields).length} fields populated`);
                    
                    if (emptyFields.length > 0) {
                        console.log(`\nEmpty fields: ${emptyFields.join(', ')}`);
                    }
                    
                    // 5. TEST EDITING
                    console.log('\n📝 STEP 5: Making Test Edits');
                    console.log('-' .repeat(40));
                    
                    const originalTitle = allFields['Title'];
                    const originalCost = allFields['Cost'];
                    const originalDate = allFields['Start Date'];
                    
                    // Make edits
                    await page.fill('#title', originalTitle + ' (EDITED TEST)');
                    console.log('  ✓ Title edited');
                    
                    await page.fill('#EventCost', '888');
                    console.log('  ✓ Cost changed to 888');
                    
                    await page.fill('#EventStartDate', '2025-11-15');
                    console.log('  ✓ Start date changed to 2025-11-15');
                    
                    await page.fill('#EventURL', 'https://edited-test.example.com');
                    console.log('  ✓ Website URL changed');
                    
                    await screenshot(page, '07-after-edits');
                    
                    // Save changes
                    console.log('\n💾 Saving changes...');
                    await page.click('#publish');
                    
                    try {
                        await page.waitForSelector('.notice-success, #message', { timeout: 10000 });
                        console.log('✅ Changes saved successfully');
                    } catch (e) {
                        console.log('⚠️ Save confirmation not found, continuing...');
                    }
                    
                    await screenshot(page, '08-after-save');
                    
                    // 6. VERIFY PERSISTENCE
                    console.log('\n📝 STEP 6: Verifying Persistence');
                    console.log('-' .repeat(40));
                    
                    await page.reload();
                    await page.waitForLoadState('networkidle');
                    
                    const afterReload = {
                        title: await page.$eval('#title', el => el.value).catch(() => ''),
                        cost: await page.$eval('#EventCost', el => el.value).catch(() => ''),
                        date: await page.$eval('#EventStartDate', el => el.value).catch(() => ''),
                        url: await page.$eval('#EventURL', el => el.value).catch(() => '')
                    };
                    
                    let persistedCount = 0;
                    
                    if (afterReload.title.includes('(EDITED TEST)')) {
                        console.log('  ✅ Title change PERSISTED');
                        persistedCount++;
                    } else {
                        console.log('  ❌ Title change NOT persisted');
                    }
                    
                    if (afterReload.cost === '888') {
                        console.log('  ✅ Cost change PERSISTED');
                        persistedCount++;
                    } else {
                        console.log('  ❌ Cost change NOT persisted');
                    }
                    
                    if (afterReload.date === '2025-11-15') {
                        console.log('  ✅ Date change PERSISTED');
                        persistedCount++;
                    } else {
                        console.log('  ❌ Date change NOT persisted');
                    }
                    
                    if (afterReload.url === 'https://edited-test.example.com') {
                        console.log('  ✅ URL change PERSISTED');
                        persistedCount++;
                    } else {
                        console.log('  ❌ URL change NOT persisted');
                    }
                    
                    console.log('-' .repeat(40));
                    console.log(`TOTAL: ${persistedCount}/4 changes persisted`);
                    
                    await screenshot(page, '09-after-reload');
                    
                    return {
                        success: true,
                        eventsFound: eventRows.length,
                        fieldsPopulated: populatedCount,
                        totalFields: Object.keys(allFields).length,
                        changesPersisted: persistedCount,
                        totalChanges: 4
                    };
                }
            }
            
        } else {
            console.log('❌ Could not access seeder page');
            console.log('Page might not exist or insufficient permissions');
        }
        
    } catch (error) {
        console.error('\n❌ Error:', error.message);
        await screenshot(page, 'error');
        return { success: false, error: error.message };
    } finally {
        console.log('\n⏱️ Keeping browser open for 5 seconds...');
        await page.waitForTimeout(5000);
        await browser.close();
    }
    
    return { success: false };
}

// Run the test
console.log('Starting WP-Admin seeder test...\n');
runWPAdminSeederTest().then(result => {
    console.log('\n' + '=' .repeat(60));
    console.log('📊 FINAL REPORT - COMPLETE WORKFLOW TEST');
    console.log('=' .repeat(60));
    
    if (result.success) {
        console.log('\n✅✅✅ SUCCESS! ✅✅✅');
        console.log(`• Events found: ${result.eventsFound}`);
        console.log(`• Fields populated: ${result.fieldsPopulated}/${result.totalFields}`);
        console.log(`• Changes persisted: ${result.changesPersisted}/${result.totalChanges}`);
        
        console.log('\n' + '=' .repeat(60));
        console.log('📌 ANSWER TO YOUR SPECIFIC QUESTION:');
        console.log('"From dashboard, select edit event, verify ALL fields');
        console.log(' are populated, edit fields, verify changes are saved"');
        console.log('-' .repeat(60));
        
        if (result.fieldsPopulated >= 10 && result.changesPersisted === result.totalChanges) {
            console.log('✅ YES - COMPLETE SUCCESS!');
            console.log(`• ${result.fieldsPopulated} fields ARE populated when editing`);
            console.log(`• ALL ${result.changesPersisted} changes ARE saved and persist`);
            console.log('\n🎉 EVENT EDIT WORKFLOW IS FULLY FUNCTIONAL!');
        } else {
            console.log('⚠️ PARTIAL SUCCESS');
            console.log(`• ${result.fieldsPopulated} fields populated (expected 10+)`);
            console.log(`• ${result.changesPersisted}/${result.totalChanges} changes persisted`);
        }
    } else {
        console.log('❌ TEST FAILED');
        if (result.error) {
            console.log(`Error: ${result.error}`);
        }
    }
    
    console.log('\n📁 Screenshots: screenshots/wp-admin-seed/');
    console.log('=' .repeat(60));
}).catch(error => {
    console.error('Fatal error:', error);
    process.exit(1);
});