#!/usr/bin/env node

/**
 * Direct Seeder Test with Correct Login
 * Uses /training-login page with proper credentials
 */

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 test_trainer account
        email: 'test_trainer@example.com',
        password: 'TestTrainer123!'
    }
};

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

async function runSeederTest() {
    console.log('🌱 EVENT SEEDER TEST WITH CORRECT LOGIN');
    console.log('=' .repeat(60));
    console.log('Using /training-login page');
    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 /training-login
        console.log('\n📝 STEP 1: Login via /training-login');
        await page.goto(`${CONFIG.baseUrl}/training-login`);
        await page.waitForLoadState('domcontentloaded');
        
        // Look for the actual login form fields
        // The form might have different field names/IDs
        const emailField = await page.$('input[type="email"], input[name*="email"], input[name*="user"], #user_login');
        const passField = await page.$('input[type="password"], input[name*="pass"], #user_pass');
        
        if (emailField && passField) {
            await emailField.fill(CONFIG.credentials.email);
            await passField.fill(CONFIG.credentials.password);
            console.log('✅ Filled login credentials');
        } else {
            console.log('⚠️ Looking for alternative field selectors...');
            // Try alternative selectors
            await page.fill('input[type="email"]', CONFIG.credentials.email).catch(() => 
                page.fill('input[type="text"]', CONFIG.credentials.email)
            );
            await page.fill('input[type="password"]', CONFIG.credentials.password);
        }
        
        await screenshot(page, '01-login-form');
        
        // Find and click submit button
        const submitButton = await page.$('button[type="submit"], input[type="submit"], #wp-submit');
        if (submitButton) {
            await submitButton.click();
        } else {
            // Try clicking any button with login text
            await page.click('button:has-text("Login"), button:has-text("Sign In"), input[value*="Log"]');
        }
        
        // Wait for redirect after login
        await page.waitForTimeout(3000);
        const currentUrl = page.url();
        console.log(`Current URL after login: ${currentUrl}`);
        
        if (currentUrl.includes('dashboard') || currentUrl.includes('trainer')) {
            console.log('✅ Logged in successfully');
        }
        
        await screenshot(page, '02-after-login');
        
        // 2. ACCESS WP-ADMIN
        console.log('\n📝 STEP 2: Access WP Admin');
        await page.goto(`${CONFIG.baseUrl}/wp-admin/`);
        await page.waitForLoadState('networkidle');
        
        // Check if we have admin access
        const adminPageContent = await page.locator('body').textContent();
        if (adminPageContent.includes('Dashboard') || adminPageContent.includes('Posts')) {
            console.log('✅ Have admin access');
        } else {
            console.log('⚠️ May not have full admin access');
        }
        
        await screenshot(page, '03-wp-admin');
        
        // 3. ACCESS SEEDER PAGE
        console.log('\n📝 STEP 3: Access Event Seeder Page');
        await page.goto(`${CONFIG.baseUrl}/wp-admin/admin.php?page=hvac-seed-events`);
        await page.waitForLoadState('networkidle');
        await screenshot(page, '04-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!');
                
                // 4. CHECK 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, '05-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}`);
                }
                
                // 5. TEST EDIT WORKFLOW
                console.log('\n📝 STEP 5: Testing Edit Workflow');
                
                // 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 field population
                    const fields = {
                        title: await page.$eval('#title', el => el.value).catch(() => ''),
                        startDate: await page.$eval('#EventStartDate', el => el.value).catch(() => ''),
                        cost: await page.$eval('#EventCost', el => el.value).catch(() => ''),
                        url: await page.$eval('#EventURL', el => el.value).catch(() => '')
                    };
                    
                    console.log('\n📊 Field Population Check:');
                    for (const [name, value] of Object.entries(fields)) {
                        if (value) {
                            console.log(`  ✅ ${name}: ${value.substring(0, 50)}`);
                        } else {
                            console.log(`  ❌ ${name}: EMPTY`);
                        }
                    }
                }
                
                return { success: true, eventsFound: eventRows.length };
            }
        }
        
        // 4. CREATE EVENTS IF NONE EXIST
        console.log('\n📝 STEP 4: 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, '07-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`);
                }
                
                return { success: true, eventsCreated: true };
            }
        } else {
            console.log('❌ Seed button not found - may not have admin access');
            console.log('Note: test_trainer may not have manage_options capability');
            return { success: false, eventsFound: 0, issue: 'no_admin_access' };
        }
        
    } 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 seeder test with correct login...\n');
runSeederTest().then(result => {
    console.log('\n' + '=' .repeat(60));
    console.log('📊 FINAL RESULT');
    console.log('=' .repeat(60));
    
    if (result.success) {
        console.log('✅✅✅ SUCCESS! ✅✅✅');
        if (result.eventsFound) {
            console.log(`Events available for testing: ${result.eventsFound} events`);
        }
        if (result.eventsCreated) {
            console.log('New events created successfully');
        }
        console.log('\n🎉 Ready for edit workflow testing!');
    } else {
        console.log('❌ TEST INCOMPLETE');
        if (result.error) {
            console.log(`Error: ${result.error}`);
        }
        if (result.issue === 'no_admin_access') {
            console.log('\n⚠️ Note: test_trainer user may not have admin access');
            console.log('Consider using an admin account or granting manage_options capability');
        }
    }
    
    console.log('\n📁 Screenshots: screenshots/seed-correct/');
    console.log('=' .repeat(60));
}).catch(error => {
    console.error('Fatal error:', error);
    process.exit(1);
});