#!/usr/bin/env node

/**
 * Direct Seeder Test
 * Simple test to login and seed events via admin page
 */

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: {
        // Use ben@upskillhvac.com (admin) account
        email: 'ben@upskillhvac.com',
        password: 'Stage123!'
    }
};

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

async function runSeederTest() {
    console.log('🌱 DIRECT EVENT SEEDER TEST');
    console.log('=' .repeat(60));
    console.log('Testing: Login → Access Seeder → Create Events → Verify');
    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
        console.log('\n📝 STEP 1: Login as admin');
        await page.goto(`${CONFIG.baseUrl}/wp-login.php`);
        await page.waitForLoadState('domcontentloaded');
        
        await page.fill('#user_login', CONFIG.credentials.email);
        await page.fill('#user_pass', CONFIG.credentials.password);
        await screenshot(page, '01-login-form');
        
        await page.click('#wp-submit');
        
        // Wait for successful login with longer timeout
        await page.waitForURL('**/wp-admin/**', { timeout: 30000 });
        console.log('✅ Logged in successfully');
        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();
        
        // Check if events already exist
        const eventsMatch = pageContent.match(/Found\s+<strong>(\d+)<\/strong>\s+events/);
        if (eventsMatch) {
            const existingCount = parseInt(eventsMatch[1]);
            console.log(`Found ${existingCount} existing events`);
            
            if (existingCount > 0) {
                console.log('✅ Events already exist - seeder is working!');
                
                // 3. CHECK EVENTS 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, '04-events-list');
                
                const eventRows = await page.$$('tbody#the-list tr');
                console.log(`✅ Found ${eventRows.length} events in admin list`);
                
                // List first few events
                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(`  • Event ${i+1}: ${title}`);
                }
                
                return { success: true, eventsFound: eventRows.length };
            }
        }
        
        // 3. CREATE EVENTS IF NONE EXIST
        console.log('\n📝 STEP 3: Creating Test Events');
        
        // Look for seed button
        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();
            
            // Wait for redirect/reload
            await page.waitForLoadState('networkidle');
            await page.waitForTimeout(2000);
            await screenshot(page, '05-after-seed');
            
            // Check for success message
            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`);
                }
                
                // 4. VERIFY IN EVENTS LIST
                console.log('\n📝 STEP 4: 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, '06-events-list-after');
                
                const eventRows = await page.$$('tbody#the-list tr');
                console.log(`✅ Found ${eventRows.length} events in admin list`);
                
                return { success: true, eventsFound: eventRows.length };
            }
        } else {
            console.log('❌ Seed button not found');
            return { success: false, eventsFound: 0 };
        }
        
    } catch (error) {
        console.error('\n❌ Error:', error.message);
        await screenshot(page, 'error');
        return { success: false, error: error.message };
    } finally {
        // Keep browser open for 5 seconds to review
        console.log('\n⏱️ Keeping browser open for 5 seconds...');
        await page.waitForTimeout(5000);
        await browser.close();
    }
}

// Run the test
console.log('Starting direct seeder test...\n');
runSeederTest().then(result => {
    console.log('\n' + '=' .repeat(60));
    console.log('📊 FINAL RESULT');
    console.log('=' .repeat(60));
    
    if (result.success) {
        console.log('✅✅✅ SUCCESS! ✅✅✅');
        console.log(`Events are now available for testing: ${result.eventsFound} events`);
        console.log('\n🎉 You can now run the edit workflow test!');
    } else {
        console.log('❌ TEST FAILED');
        if (result.error) {
            console.log(`Error: ${result.error}`);
        }
    }
    
    console.log('\n📁 Screenshots: screenshots/seed-test/');
    console.log('=' .repeat(60));
}).catch(error => {
    console.error('Fatal error:', error);
    process.exit(1);
});