/**
 * Test trainer event editing permissions
 */

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

async function testTrainerEventPermissions() {
    console.log('🔍 Testing Trainer Event Permissions...\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 test_trainer
        console.log('1️⃣ Logging in as test_trainer...');
        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');
        
        // Step 2: Go to event manage page to find an event
        console.log('\n2️⃣ Looking for trainer\'s events...');
        await page.goto(`${baseUrl}/trainer/event/manage/`);
        await page.waitForLoadState('networkidle');
        
        // Check if there are any events listed
        const eventLinks = await page.$$eval('.hvac-event-table a[href*="event_id="]', links => 
            links.map(link => {
                const href = link.getAttribute('href');
                const match = href.match(/event_id=(\d+)/);
                return {
                    id: match ? match[1] : null,
                    text: link.textContent.trim(),
                    href: href
                };
            })
        );
        
        console.log(`Found ${eventLinks.length} events:`, eventLinks);
        
        // Step 3: Try to create a new event
        console.log('\n3️⃣ Testing new event creation...');
        await page.goto(`${baseUrl}/trainer/event/edit/`);
        await page.waitForLoadState('networkidle');
        
        const newEventCheck = await page.evaluate(() => {
            const bodyText = document.body.innerText;
            const hasForm = document.querySelector('input[name="post_title"]') !== null;
            const hasPermissionError = bodyText.includes('permission') || bodyText.includes('Permission');
            const pageTitle = document.querySelector('h1')?.innerText || '';
            
            return { 
                hasForm, 
                hasPermissionError, 
                pageTitle,
                canCreate: hasForm && !hasPermissionError
            };
        });
        
        console.log('New event creation check:');
        console.log('  - Has form:', newEventCheck.hasForm);
        console.log('  - Has permission error:', newEventCheck.hasPermissionError);
        console.log('  - Page title:', newEventCheck.pageTitle);
        console.log('  - Can create:', newEventCheck.canCreate ? '✅ YES' : '❌ NO');
        
        // Step 4: If there are events, try to edit the first one
        if (eventLinks.length > 0 && eventLinks[0].id) {
            const eventId = eventLinks[0].id;
            console.log(`\n4️⃣ Testing edit of event ID ${eventId}...`);
            
            await page.goto(`${baseUrl}/trainer/event/edit/?event_id=${eventId}`);
            await page.waitForLoadState('networkidle');
            
            const editCheck = await page.evaluate(() => {
                const bodyText = document.body.innerText;
                const hasForm = document.querySelector('input[name="post_title"]') !== null;
                const hasPermissionError = bodyText.includes('permission') || bodyText.includes('Permission');
                const eventTitle = document.querySelector('input[name="post_title"]')?.value || '';
                
                return { 
                    hasForm, 
                    hasPermissionError, 
                    eventTitle,
                    canEdit: hasForm && !hasPermissionError
                };
            });
            
            console.log('Edit event check:');
            console.log('  - Has form:', editCheck.hasForm);
            console.log('  - Has permission error:', editCheck.hasPermissionError);
            console.log('  - Event title:', editCheck.eventTitle);
            console.log('  - Can edit:', editCheck.canEdit ? '✅ YES' : '❌ NO');
        }
        
        // Step 5: Try to edit a random event (likely not owned)
        console.log('\n5️⃣ Testing edit of event not owned by trainer (ID 6161)...');
        await page.goto(`${baseUrl}/trainer/event/edit/?event_id=6161`);
        await page.waitForLoadState('networkidle');
        
        const otherEventCheck = await page.evaluate(() => {
            const bodyText = document.body.innerText;
            const hasForm = document.querySelector('input[name="post_title"]') !== null;
            const hasPermissionError = bodyText.includes('permission') || bodyText.includes('Permission');
            
            return { 
                hasForm, 
                hasPermissionError,
                canEdit: hasForm && !hasPermissionError
            };
        });
        
        console.log('Other event check:');
        console.log('  - Has form:', otherEventCheck.hasForm);
        console.log('  - Has permission error:', otherEventCheck.hasPermissionError);
        console.log('  - Can edit:', otherEventCheck.canEdit ? '✅ YES (BUG!)' : '❌ NO (Correct)');
        
        // Summary
        console.log('\n📋 PERMISSION TEST SUMMARY:');
        console.log('================================');
        console.log(`✅ Can create new events: ${newEventCheck.canCreate ? 'YES' : 'NO'}`);
        if (eventLinks.length > 0) {
            console.log(`✅ Can edit own events: Needs verification`);
        }
        console.log(`✅ Cannot edit others' events: ${!otherEventCheck.canEdit ? 'YES (Secure)' : 'NO (Security Issue)'}`);
        
        // Take screenshot
        await page.screenshot({ 
            path: `trainer-permissions-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('\n📸 Screenshot saved');
        
    } catch (error) {
        console.error('\n❌ Test failed:', error.message);
        
        await page.screenshot({ 
            path: `error-permissions-${Date.now()}.png`,
            fullPage: true 
        });
    } finally {
        console.log('\n⏸️ Keeping browser open for inspection...');
        await page.waitForTimeout(10000);
        await browser.close();
    }
}

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