#!/usr/bin/env node

/**
 * Test Organizer Management with Admin User
 */

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

const config = {
    BASE_URL: process.env.BASE_URL || 'http://localhost:8080',
    HEADLESS: process.env.HEADLESS !== 'false'
};

async function testAsAdmin() {
    console.log('🔑 Testing Organizer Management as Admin User');
    console.log('============================================\n');
    
    const browser = await chromium.launch({ 
        headless: config.HEADLESS,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    
    const page = await browser.newPage();
    
    try {
        // Login as admin
        console.log('1. Logging in as WordPress admin...');
        await page.goto(`${config.BASE_URL}/wp-admin/`);
        await page.waitForLoadState('networkidle');
        
        if (page.url().includes('wp-login.php')) {
            await page.fill('#user_login', 'testadmin');
            await page.fill('#user_pass', 'AdminPass123!');
            await page.click('#wp-submit');
            await page.waitForLoadState('networkidle');
            
            if (page.url().includes('wp-admin')) {
                console.log('   ✅ Admin login successful');
            } else {
                console.log('   ❌ Admin login failed');
                return;
            }
        } else {
            console.log('   ✅ Already logged in as admin');
        }
        
        // Test organizer pages as admin
        console.log('\n2. Testing organizer list page as admin...');
        const listResponse = await page.goto(`${config.BASE_URL}/trainer/organizer/list/`);
        await page.waitForLoadState('networkidle');
        await page.waitForTimeout(3000); // Allow time for shortcode processing
        
        console.log(`   Status: ${listResponse.status()}`);
        console.log(`   URL: ${page.url()}`);
        console.log(`   Title: "${await page.title()}"`);
        
        if (listResponse.status() === 200 && !page.url().includes('login')) {
            console.log('   ✅ Organizer list accessible as admin');
            
            const content = await page.content();
            const hasShortcode = content.includes('[hvac_trainer_organizers_list]');
            const hasContainer = content.includes('hvac-organizers-list');
            const hasTable = content.includes('hvac-organizers-table');
            
            console.log(`   - Unprocessed shortcode: ${hasShortcode ? 'Yes ❌' : 'No ✅'}`);
            console.log(`   - Has container: ${hasContainer ? 'Yes ✅' : 'No ❌'}`);
            console.log(`   - Has table: ${hasTable ? 'Yes ✅' : 'No ❌'}`);
            
            if (hasShortcode) {
                console.log('   ⚠️ Shortcode not being processed - plugin issue');
                
                // Let's debug what's in the content
                const lines = content.split('\\n');
                const shortcodeLine = lines.find(line => line.includes('[hvac_trainer_organizers_list]'));
                if (shortcodeLine) {
                    console.log(`   Debug: Shortcode found in: ${shortcodeLine.substring(0, 100)}...`);
                }
            }
        } else {
            console.log('   ❌ Organizer list not accessible even as admin');
        }
        
        console.log('\n3. Testing organizer manage page as admin...');
        const manageResponse = await page.goto(`${config.BASE_URL}/trainer/organizer/manage/`);
        await page.waitForLoadState('networkidle');
        await page.waitForTimeout(3000); // Allow time for shortcode processing
        
        console.log(`   Status: ${manageResponse.status()}`);
        console.log(`   URL: ${page.url()}`);
        console.log(`   Title: "${await page.title()}"`);
        
        if (manageResponse.status() === 200 && !page.url().includes('login')) {
            console.log('   ✅ Organizer manage accessible as admin');
            
            const content = await page.content();
            const hasShortcode = content.includes('[hvac_trainer_organizer_manage]');
            const hasContainer = content.includes('hvac-organizer-manage');
            const hasForm = content.includes('hvac-organizer-form');
            
            console.log(`   - Unprocessed shortcode: ${hasShortcode ? 'Yes ❌' : 'No ✅'}`);
            console.log(`   - Has container: ${hasContainer ? 'Yes ✅' : 'No ❌'}`);
            console.log(`   - Has form: ${hasForm ? 'Yes ✅' : 'No ❌'}`);
            
            // Check if form elements are visible
            const formVisible = await page.locator('#hvac-organizer-form').isVisible();
            console.log(`   - Form visible: ${formVisible ? 'Yes ✅' : 'No ❌'}`);
            
            if (formVisible) {
                const nameField = await page.locator('#org_name').isVisible();
                console.log(`   - Name field visible: ${nameField ? 'Yes ✅' : 'No ❌'}`);
            }
        } else {
            console.log('   ❌ Organizer manage not accessible even as admin');
        }
        
        // Test if shortcodes are working at all
        console.log('\n4. Testing shortcode functionality...');
        
        // Let's check if HVAC classes are loaded
        const classCheckScript = `
            if (typeof do_shortcode === 'undefined') {
                'WordPress shortcode system not available';
            } else {
                'WordPress system available';
            }
        `;
        
        // Check in WordPress admin area
        await page.goto(`${config.BASE_URL}/wp-admin/`);
        await page.waitForLoadState('networkidle');
        
        // Use the admin bar to test if we're properly authenticated
        const adminBar = await page.locator('#wpadminbar').isVisible();
        console.log(`   WordPress admin bar visible: ${adminBar ? 'Yes ✅' : 'No ❌'}`);
        
        // Try to access plugin admin page if it exists
        try {
            await page.goto(`${config.BASE_URL}/wp-admin/admin.php?page=hvac-settings`, {
                waitUntil: 'networkidle',
                timeout: 5000
            });
            
            if (!page.url().includes('wp-login.php')) {
                console.log('   ✅ Can access WordPress admin area');
            }
        } catch (error) {
            console.log('   ⚠️ Plugin admin page may not exist');
        }
        
    } catch (error) {
        console.error(`❌ Test error: ${error.message}`);
    } finally {
        await browser.close();
    }
}

testAsAdmin();