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

(async () => {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage();

  try {
    console.log('=== Testing TEC Community Events with test_trainer ===\n');

    // 1. Login as test_trainer
    console.log('1. Logging in as test_trainer...');
    await page.goto('https://upskill-staging.measurequick.com/training-login/');
    await page.waitForLoadState('networkidle');

    // Fill login form
    await page.fill('input[name="log"], input[name="username"], input#user_login', 'test_trainer');
    await page.fill('input[name="pwd"], input[name="password"], input#user_pass', 'TestTrainer123!');
    
    // Click login button
    await page.click('input[type="submit"], button[type="submit"]');
    await page.waitForLoadState('networkidle');
    
    const currentUrl = page.url();
    console.log('   Redirected to:', currentUrl);

    // 2. Navigate to TEC Network Events page
    console.log('\n2. Navigating to TEC Network Events page...');
    await page.goto('https://upskill-staging.measurequick.com/events/network/');
    await page.waitForLoadState('networkidle');

    // Check for error messages
    const bodyText = await page.textContent('body');
    
    if (bodyText.includes('500') || bodyText.includes('Internal Server Error')) {
      console.log('   ❌ ERROR: 500 Internal Server Error on /events/network/');
      
      // Get more error details
      const errorDetails = await page.evaluate(() => {
        const pre = document.querySelector('pre');
        return pre ? pre.textContent : null;
      });
      
      if (errorDetails) {
        console.log('   Error details:', errorDetails.substring(0, 200));
      }
    } else if (bodyText.includes('404') || bodyText.includes('Not Found')) {
      console.log('   ❌ ERROR: 404 Not Found on /events/network/');
    } else if (bodyText.includes('You must be logged in')) {
      console.log('   ⚠️  Authentication required message shown');
    } else {
      console.log('   ✅ Page loaded successfully');
      
      // Check if any events are displayed
      const hasEvents = await page.evaluate(() => {
        const eventLinks = document.querySelectorAll('a[href*="/event/"], .tribe-events-list-event-title, .event-title');
        return eventLinks.length > 0;
      });
      
      if (hasEvents) {
        console.log('   ✅ Events are displayed on the page');
        
        // Try to find an edit link
        const editLinks = await page.$$eval('a[href*="/edit/"]', links => 
          links.map(link => ({ text: link.textContent, href: link.href }))
        );
        
        if (editLinks.length > 0) {
          console.log('   ✅ Found edit links:', editLinks.length);
          editLinks.forEach(link => {
            console.log(`      - ${link.text}: ${link.href}`);
          });
        } else {
          console.log('   ⚠️  No edit links found on the page');
        }
      } else {
        console.log('   ⚠️  No events displayed on the page');
      }
    }

    // 3. Try to access Add Event page
    console.log('\n3. Testing Add Event page...');
    await page.goto('https://upskill-staging.measurequick.com/events/network/add/');
    await page.waitForLoadState('networkidle');

    const addPageText = await page.textContent('body');
    
    if (addPageText.includes('500') || addPageText.includes('Internal Server Error')) {
      console.log('   ❌ ERROR: 500 Internal Server Error on /events/network/add/');
    } else if (addPageText.includes('404') || addPageText.includes('Not Found')) {
      console.log('   ❌ ERROR: 404 Not Found on /events/network/add/');
    } else {
      console.log('   ✅ Add Event page loaded');
      
      // Check for form fields
      const hasFormFields = await page.evaluate(() => {
        const titleField = document.querySelector('input[name*="title"], input[name*="EventTitle"], #post_title');
        const descField = document.querySelector('textarea[name*="description"], textarea[name*="EventDescription"], #post_content');
        return { hasTitle: !!titleField, hasDescription: !!descField };
      });
      
      if (hasFormFields.hasTitle && hasFormFields.hasDescription) {
        console.log('   ✅ Event form fields are present');
        console.log('      - Title field: Present');
        console.log('      - Description field: Present');
      } else {
        console.log('   ⚠️  Some form fields are missing');
        console.log('      - Title field:', hasFormFields.hasTitle ? 'Present' : 'Missing');
        console.log('      - Description field:', hasFormFields.hasDescription ? 'Present' : 'Missing');
      }
    }

    // 4. Try to edit one of the created events
    console.log('\n4. Testing Edit Event functionality...');
    // Use one of the event IDs we created (6074)
    await page.goto('https://upskill-staging.measurequick.com/events/network/edit/6074/');
    await page.waitForLoadState('networkidle');

    const editPageText = await page.textContent('body');
    
    if (editPageText.includes('500') || editPageText.includes('Internal Server Error')) {
      console.log('   ❌ ERROR: 500 Internal Server Error on edit page');
    } else if (editPageText.includes('404') || editPageText.includes('Not Found')) {
      console.log('   ❌ ERROR: 404 Not Found - edit page not accessible');
    } else if (editPageText.includes('not authorized') || editPageText.includes('permission')) {
      console.log('   ⚠️  Permission denied to edit this event');
    } else {
      console.log('   ✅ Edit page loaded');
      
      // Check if form is populated with event data
      const eventData = await page.evaluate(() => {
        const titleField = document.querySelector('input[name*="title"], input[name*="EventTitle"], #post_title');
        const descField = document.querySelector('textarea[name*="description"], textarea[name*="EventDescription"], #post_content');
        
        return {
          title: titleField ? titleField.value : null,
          description: descField ? descField.value : null,
          hasTitle: !!titleField,
          hasDescription: !!descField
        };
      });
      
      if (eventData.hasTitle && eventData.title) {
        console.log('   ✅ Event title is populated:', eventData.title);
      } else if (eventData.hasTitle) {
        console.log('   ⚠️  Title field exists but is empty');
      } else {
        console.log('   ❌ Title field not found');
      }
      
      if (eventData.hasDescription && eventData.description) {
        console.log('   ✅ Event description is populated');
      } else if (eventData.hasDescription) {
        console.log('   ⚠️  Description field exists but is empty');
      } else {
        console.log('   ❌ Description field not found');
      }
    }

    // 5. Check our custom manage event page
    console.log('\n5. Checking custom manage event page...');
    await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/');
    await page.waitForLoadState('networkidle');

    const managePageText = await page.textContent('body');
    console.log('   Page title:', await page.title());
    
    // Check if our links to TEC pages are present
    const hasLinks = await page.evaluate(() => {
      const addLink = document.querySelector('a[href*="/events/network/add/"]');
      const viewLink = document.querySelector('a[href*="/events/network/"]');
      return { hasAddLink: !!addLink, hasViewLink: !!viewLink };
    });
    
    if (hasLinks.hasAddLink && hasLinks.hasViewLink) {
      console.log('   ✅ Navigation links to TEC pages are present');
    } else {
      console.log('   ⚠️  Some navigation links are missing');
      console.log('      - Add Event link:', hasLinks.hasAddLink ? 'Present' : 'Missing');
      console.log('      - View Events link:', hasLinks.hasViewLink ? 'Present' : 'Missing');
    }

    console.log('\n=== Test Summary ===');
    console.log('Test user: test_trainer');
    console.log('Test events created: 6074, 6075, 6076');
    console.log('\nTEC Community Events URLs:');
    console.log('- Network page: /events/network/');
    console.log('- Add event: /events/network/add/');
    console.log('- Edit event: /events/network/edit/{id}/');

  } catch (error) {
    console.error('Test error:', error);
  } finally {
    await browser.close();
  }
})();