/**
 * Test to check if the edit page actually exists and what its settings are
 */

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

async function testPageExists() {
    console.log('🔍 Testing Page Existence...\\n');
    
    const browser = await chromium.launch({
        headless: false,
        args: ['--disable-dev-shm-usage', '--no-sandbox']
    });
    
    const context = await browser.newContext({
        viewport: { width: 1280, height: 720 }
    });
    
    const page = await context.newPage();
    const baseUrl = 'https://upskill-staging.measurequick.com';
    
    try {
        // Step 1: Login as admin to check WordPress admin
        console.log('1️⃣ Logging in as admin...');
        await page.goto(`${baseUrl}/wp-admin/`);
        await page.waitForLoadState('networkidle');
        
        // Check if already logged in or need to login
        const hasLoginForm = await page.$('input[name="log"]') !== null;
        
        if (hasLoginForm) {
            console.log('   Admin login required - checking page via direct URL instead...');
            
            // Step 2: Try to access the page directly and see what happens
            console.log('\\n2️⃣ Checking page directly...');
            await page.goto(`${baseUrl}/trainer/event/edit/`);
            await page.waitForLoadState('networkidle');
            
            const currentUrl = page.url();
            console.log('   Current URL:', currentUrl);
            
            // Check what type of page we get
            const pageInfo = await page.evaluate(() => {
                const title = document.title;
                const bodyClasses = document.body.className;
                const hasNotFound = document.body.innerHTML.includes('404') || 
                                   document.body.innerHTML.includes('not found') ||
                                   document.body.innerHTML.includes('Not Found');
                const hasLoginForm = document.querySelector('input[name="log"]') !== null;
                
                return {
                    title,
                    bodyClasses,
                    hasNotFound,
                    hasLoginForm
                };
            });
            
            console.log('   Page title:', pageInfo.title);
            console.log('   Body classes:', pageInfo.bodyClasses);
            console.log('   Has 404 content:', pageInfo.hasNotFound);
            console.log('   Has login form:', pageInfo.hasLoginForm);
            
            if (pageInfo.hasNotFound) {
                console.log('\\n❌ Page returns 404 - it does not exist!');
            } else if (pageInfo.hasLoginForm) {
                console.log('\\n🔄 Page redirects to login - access control issue');
            } else {
                console.log('\\n✅ Page exists and loads content');
            }
            
        } else {
            console.log('\\n2️⃣ Already logged in to admin - checking pages...');
            
            // Go to pages list
            await page.goto(`${baseUrl}/wp-admin/edit.php?post_type=page`);
            await page.waitForLoadState('networkidle');
            
            // Search for edit page
            const searchBox = await page.$('input[name="s"]');
            if (searchBox) {
                await searchBox.fill('Edit Event');
                await page.press('input[name="s"]', 'Enter');
                await page.waitForLoadState('networkidle');
                
                // Check results
                const pageExists = await page.evaluate(() => {
                    const rows = document.querySelectorAll('.wp-list-table tbody tr');
                    for (const row of rows) {
                        const titleCell = row.querySelector('.column-title');
                        if (titleCell && titleCell.textContent.includes('Edit Event')) {
                            const link = titleCell.querySelector('a');
                            const id = link ? link.href.match(/post=(\\d+)/)?.[1] : null;
                            return {
                                exists: true,
                                title: titleCell.textContent.trim(),
                                id: id
                            };
                        }
                    }
                    return { exists: false };
                });
                
                if (pageExists.exists) {
                    console.log(`\\n✅ Page exists: "${pageExists.title}" (ID: ${pageExists.id})`);
                } else {
                    console.log('\\n❌ Page "Edit Event" not found in WordPress admin');
                }
            }
        }
        
        // Step 3: Test URL patterns
        console.log('\\n3️⃣ Testing URL patterns...');
        const testUrls = [
            '/trainer/event/edit/',
            '/trainer/event/edit',
            '/trainer/event/manage/',
            '/trainer/dashboard/'
        ];
        
        for (const testUrl of testUrls) {
            console.log(`\\n   Testing: ${testUrl}`);
            await page.goto(`${baseUrl}${testUrl}`);
            await page.waitForLoadState('networkidle', { timeout: 10000 });
            
            const result = await page.evaluate(() => {
                const currentUrl = window.location.href;
                const hasLoginForm = document.querySelector('input[name="log"]') !== null;
                const hasNotFound = document.body.innerHTML.includes('404') || 
                                   document.body.innerHTML.includes('not found');
                
                return { currentUrl, hasLoginForm, hasNotFound };
            });
            
            console.log(`     Final URL: ${result.currentUrl}`);
            console.log(`     Redirected to login: ${result.hasLoginForm}`);
            console.log(`     404 error: ${result.hasNotFound}`);
        }
        
        // Take screenshot
        await page.screenshot({ 
            path: `page-exists-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('\\n📸 Screenshot saved');
        
    } catch (error) {
        console.error('\\n❌ Test failed:', error.message);
        
        await page.screenshot({ 
            path: `error-page-exists-${Date.now()}.png`,
            fullPage: true 
        });
    } finally {
        console.log('\\n⏸️ Keeping browser open for inspection...');
        await page.waitForTimeout(10000);
        await browser.close();
    }
}

// Run test
testPageExists()
    .then(() => {
        console.log('\\n✨ Test completed!');
        process.exit(0);
    })
    .catch(error => {
        console.error('\\n💥 Test failed:', error);
        process.exit(1);
    });