/**
 * Test to find events owned by test_trainer
 */

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

async function testTrainerEvents() {
    console.log('🔍 Finding test_trainer events...\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 {
        // Login as test_trainer
        console.log('1️⃣ Logging in...');
        await page.goto(`${baseUrl}/training-login/`);
        await page.waitForLoadState('networkidle');
        
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        await page.press('input[name="pwd"]', 'Enter');
        
        await page.waitForURL('**/trainer/dashboard/**', { timeout: 10000 });
        console.log('✅ Login successful');
        
        // Go to event manage page to see what events are available
        console.log('\n2️⃣ Checking trainer events...');
        await page.goto(`${baseUrl}/trainer/event/manage/`);
        await page.waitForLoadState('networkidle');
        
        const eventsInfo = await page.evaluate(() => {
            // Look for event links or IDs in the page
            const links = Array.from(document.querySelectorAll('a')).filter(link => 
                link.href.includes('event') && (link.href.includes('edit') || link.href.includes('id='))
            );
            
            const eventIds = [];
            links.forEach(link => {
                const match = link.href.match(/[\?&]event_id=(\d+)/);
                if (match) {
                    eventIds.push({
                        id: match[1],
                        text: link.textContent.trim(),
                        href: link.href
                    });
                }
            });
            
            // Also check the page content for any event information
            const pageText = document.body.innerText;
            const hasEvents = pageText.includes('event') || pageText.includes('Event');
            
            return {
                eventIds,
                hasEvents,
                pageSnippet: pageText.substring(0, 500)
            };
        });
        
        console.log('   Found event IDs:', eventsInfo.eventIds);
        console.log('   Page has event content:', eventsInfo.hasEvents);
        console.log('   Page content preview:');
        console.log('   ' + eventsInfo.pageSnippet.replace(/\n/g, '\n   '));
        
        // Test a specific valid event ID if found
        if (eventsInfo.eventIds.length > 0) {
            const firstEventId = eventsInfo.eventIds[0].id;
            console.log(`\n3️⃣ Testing edit access for event ${firstEventId}...`);
            
            await page.goto(`${baseUrl}/trainer/event/edit/?event_id=${firstEventId}`);
            await page.waitForLoadState('networkidle');
            
            const editResult = await page.evaluate(() => {
                const title = document.title;
                const hasError = title.includes('Error') || document.body.innerText.includes('permission');
                const hasForm = document.querySelector('input[name="post_title"]') !== null;
                
                return { title, hasError, hasForm };
            });
            
            console.log(`   Title: ${editResult.title}`);
            console.log(`   Has error: ${editResult.hasError}`);
            console.log(`   Has edit form: ${editResult.hasForm}`);
            
            if (editResult.hasForm) {
                console.log('   ✅ Can edit this event');
            } else if (editResult.hasError) {
                console.log('   ❌ Permission denied for this event');
            }
        } else {
            console.log('\n❌ No events found for test_trainer');
        }
        
        // Test creating a new event first, then editing it
        console.log('\n4️⃣ Testing create-then-edit workflow...');
        await page.goto(`${baseUrl}/trainer/event/edit/`);
        await page.waitForLoadState('networkidle');
        
        // Fill out a minimal event form
        await page.fill('input[name="post_title"]', 'Test Event for Edit');
        await page.fill('textarea[name="post_content"]', 'This is a test event');
        
        // Submit the form
        await page.click('input[type="submit"], button[type="submit"]');
        await page.waitForLoadState('networkidle');
        
        const createResult = await page.evaluate(() => {
            const currentUrl = window.location.href;
            const eventIdMatch = currentUrl.match(/[\?&]event_id=(\d+)/);
            return {
                currentUrl,
                eventId: eventIdMatch ? eventIdMatch[1] : null
            };
        });
        
        if (createResult.eventId) {
            console.log(`   ✅ Created new event: ${createResult.eventId}`);
            console.log(`   Now testing edit access...`);
            
            // The page should already be showing the edit form for the new event
            const finalEditTest = await page.evaluate(() => {
                const hasForm = document.querySelector('input[name="post_title"]') !== null;
                const title = document.title;
                return { hasForm, title };
            });
            
            console.log(`   Edit form available: ${finalEditTest.hasForm}`);
            console.log(`   Page title: ${finalEditTest.title}`);
            
            if (finalEditTest.hasForm) {
                console.log('   ✅ SUCCESS: Create-then-edit workflow works!');
            }
        } else {
            console.log('   ❌ Event creation failed');
        }
        
        await page.screenshot({ 
            path: `trainer-events-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('\n📸 Screenshot saved');
        
    } catch (error) {
        console.error('\n❌ Test failed:', error.message);
        
        await page.screenshot({ 
            path: `error-trainer-events-${Date.now()}.png`,
            fullPage: true 
        });
    } finally {
        console.log('\n⏸️ Keeping browser open for inspection...');
        await page.waitForTimeout(10000);
        await browser.close();
    }
}

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