/**
 * Test creating an event then editing it as the same trainer
 */

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

async function testCreateAndEditEvent() {
    console.log('🔍 Testing Create and Edit Event Workflow...\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: Create a new event
        console.log('\n2️⃣ Creating a new test event...');
        await page.goto(`${baseUrl}/trainer/event/edit/`);
        await page.waitForLoadState('networkidle');
        
        // Fill in event details
        const eventTitle = `Test Event ${Date.now()}`;
        await page.fill('input[name="post_title"]', eventTitle);
        await page.fill('textarea[name="post_excerpt"]', 'This is a test event created for permission testing');
        
        // Set dates (today)
        const today = new Date().toISOString().split('T')[0];
        await page.fill('input[name="EventStartDate"]', today);
        await page.fill('input[name="EventEndDate"]', today);
        
        // Fill venue info
        await page.fill('input[name="venue_name"]', 'Test Venue');
        await page.fill('input[name="venue_city"]', 'Test City');
        await page.fill('input[name="venue_state"]', 'TX');
        
        // Submit the form
        console.log('Submitting event creation form...');
        await page.click('button[type="submit"]');
        
        // Wait for redirect with event_id
        await page.waitForURL('**/trainer/event/edit/**', { timeout: 10000 });
        
        // Extract the event ID from URL
        const url = page.url();
        const eventIdMatch = url.match(/event_id=(\d+)/);
        const eventId = eventIdMatch ? eventIdMatch[1] : null;
        
        if (eventId) {
            console.log(`✅ Event created successfully! ID: ${eventId}`);
            console.log(`Event title: ${eventTitle}`);
            
            // Step 3: Now try to edit the same event
            console.log('\n3️⃣ Testing edit of the newly created event...');
            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 own event check:');
            console.log('  - Has form:', editCheck.hasForm);
            console.log('  - Has permission error:', editCheck.hasPermissionError);
            console.log('  - Event title loaded:', editCheck.eventTitle);
            console.log('  - Can edit own event:', editCheck.canEdit ? '✅ YES' : '❌ NO (BUG!)');
            
            // Step 4: Try to make a change and save
            if (editCheck.canEdit) {
                console.log('\n4️⃣ Testing save after edit...');
                const updatedTitle = eventTitle + ' - Updated';
                await page.fill('input[name="post_title"]', updatedTitle);
                await page.click('button[type="submit"]');
                
                // Wait for save to complete
                await page.waitForLoadState('networkidle');
                
                // Check if save was successful
                const saveCheck = await page.evaluate(() => {
                    const bodyText = document.body.innerText;
                    const hasSuccessMessage = bodyText.includes('successfully') || bodyText.includes('saved');
                    const currentTitle = document.querySelector('input[name="post_title"]')?.value || '';
                    return { hasSuccessMessage, currentTitle };
                });
                
                console.log('Save check:');
                console.log('  - Has success message:', saveCheck.hasSuccessMessage);
                console.log('  - Updated title:', saveCheck.currentTitle);
                console.log('  - Save successful:', saveCheck.hasSuccessMessage ? '✅ YES' : '❌ NO');
            }
            
            // Summary
            console.log('\n📋 CREATE AND EDIT TEST SUMMARY:');
            console.log('================================');
            console.log(`✅ Event created: ID ${eventId}`);
            console.log(`✅ Can edit own event: ${editCheck.canEdit ? 'YES' : 'NO (BUG!)'}`)
            
            if (!editCheck.canEdit) {
                console.log('\n⚠️ WARNING: Trainer cannot edit their own event!');
                console.log('This is a permission bug that needs to be fixed.');
            }
        } else {
            console.log('❌ Failed to extract event ID from redirect URL');
        }
        
        // Take screenshot
        await page.screenshot({ 
            path: `create-edit-test-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('\n📸 Screenshot saved');
        
    } catch (error) {
        console.error('\n❌ Test failed:', error.message);
        
        await page.screenshot({ 
            path: `error-create-edit-${Date.now()}.png`,
            fullPage: true 
        });
    } finally {
        console.log('\n⏸️ Keeping browser open for inspection...');
        await page.waitForTimeout(10000);
        await browser.close();
    }
}

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