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

// Constants
const STAGING_URL = 'https://wordpress-974670-5399585.cloudwaysapps.com';
const LOGIN_URL = `${STAGING_URL}/community-login/`;
const DASHBOARD_URL = `${STAGING_URL}/hvac-dashboard/`;
const USERNAME = 'test_trainer';
const PASSWORD = 'Test123!';

// Main function to run tests
async function runCertificateTests() {
  console.log('Starting certificate tests...');
  
  // Launch browser
  const browser = await chromium.launch({ headless: false });
  const context = await browser.newContext({
    viewport: { width: 1280, height: 720 }
  });
  const page = await context.newPage();
  
  try {
    // Login
    console.log('Logging in...');
    await page.goto(LOGIN_URL);
    await page.fill('#user_login', USERNAME);
    await page.fill('#user_pass', PASSWORD);
    await page.click('#wp-submit');
    await page.waitForLoadState('networkidle');
    
    // Verify login successful
    if (!page.url().includes('hvac-dashboard')) {
      throw new Error('Login failed');
    }
    console.log('Login successful');
    
    // Test 1: Navigate to Generate Certificates page
    console.log('\nTest 1: Navigating to Generate Certificates page...');
    await testGenerateCertificatesNavigation(page);
    
    // Test 2: Navigate to Certificate Reports page
    console.log('\nTest 2: Navigating to Certificate Reports page...');
    await testCertificateReportsNavigation(page);
    
    // Test 3: Test certificate filtering
    console.log('\nTest 3: Testing certificate filtering...');
    await testCertificateFiltering(page);
    
    console.log('\nAll tests completed successfully!');
  } catch (error) {
    console.error(`Test failed: ${error.message}`);
  } finally {
    // Close browser
    await browser.close();
  }
}

// Test navigation to Generate Certificates page
async function testGenerateCertificatesNavigation(page) {
  // Navigate to dashboard first
  await page.goto(DASHBOARD_URL);
  await page.waitForLoadState('networkidle');
  
  // Look for Generate Certificates link
  const generateLink = page.locator('a:has-text("Generate Certificates")');
  if (await generateLink.isVisible()) {
    await generateLink.click();
    await page.waitForLoadState('networkidle');
    
    // Check page title
    const title = await page.title();
    console.log(`Page title: ${title}`);
    
    // Check for event dropdown
    const eventDropdown = page.locator('#event_id');
    if (await eventDropdown.isVisible()) {
      console.log('Event dropdown found');
      
      // Count options
      const optionCount = await page.locator('#event_id option').count();
      console.log(`Event options: ${optionCount}`);
      
      // If we have options, select the first one
      if (optionCount > 1) {
        await eventDropdown.selectOption({ index: 1 });
        await page.waitForLoadState('networkidle');
        
        // Get the selected event name
        const selectedEventName = await page.locator('#event_id option:checked').textContent();
        console.log(`Selected event: ${selectedEventName}`);
      }
    } else {
      console.log('Event dropdown not found');
    }
    
    console.log('Generate Certificates page navigation test passed!');
    return true;
  } else {
    console.log('Generate Certificates link not found, skipping test');
    return false;
  }
}

// Test navigation to Certificate Reports page
async function testCertificateReportsNavigation(page) {
  // Navigate to dashboard first
  await page.goto(DASHBOARD_URL);
  await page.waitForLoadState('networkidle');
  
  // Look for Certificate Reports link
  const reportsLink = page.locator('a:has-text("Certificate Reports")');
  if (await reportsLink.isVisible()) {
    await reportsLink.click();
    await page.waitForLoadState('networkidle');
    
    // Check page title
    const title = await page.title();
    console.log(`Page title: ${title}`);
    
    // Check for filter form
    const filterForm = page.locator('form.hvac-certificate-filters');
    if (await filterForm.isVisible()) {
      console.log('Certificate filter form found');
    } else {
      console.log('Certificate filter form not found');
    }
    
    console.log('Certificate Reports page navigation test passed!');
    return true;
  } else {
    console.log('Certificate Reports link not found, skipping test');
    return false;
  }
}

// Test certificate filtering
async function testCertificateFiltering(page) {
  // Navigate to Certificate Reports page
  await page.goto(`${STAGING_URL}/certificate-reports/`);
  await page.waitForLoadState('networkidle');
  
  // Check for filter form
  const filterForm = page.locator('form.hvac-certificate-filters');
  if (await filterForm.isVisible()) {
    // Check if event filter exists
    const eventFilter = page.locator('#filter_event');
    if (await eventFilter.isVisible()) {
      console.log('Event filter found');
      
      // Count options
      const optionCount = await page.locator('#filter_event option').count();
      console.log(`Event filter options: ${optionCount}`);
      
      // If we have options, select the first one
      if (optionCount > 1) {
        await eventFilter.selectOption({ index: 1 });
      }
    }
    
    // Check if attendee search exists
    const attendeeSearch = page.locator('#search_attendee');
    if (await attendeeSearch.isVisible()) {
      console.log('Attendee search found');
      
      // Try a simple search
      await attendeeSearch.fill('test');
      
      // Look for filter button
      const filterButton = page.locator('button[type="submit"]');
      if (await filterButton.isVisible()) {
        await filterButton.click();
        await page.waitForLoadState('networkidle');
        console.log('Filtered for "test"');
        
        // Get certificate count
        const certificateItems = page.locator('.hvac-certificate-item');
        const certificateCount = await certificateItems.count();
        console.log(`Found ${certificateCount} certificates with filter "test"`);
        
        // Check for reset button
        const resetButton = page.locator('button[type="reset"]');
        if (await resetButton.isVisible()) {
          await resetButton.click();
          await page.waitForLoadState('networkidle');
          console.log('Reset filters');
          
          // Get certificate count after reset
          const resetCertificateCount = await certificateItems.count();
          console.log(`Found ${resetCertificateCount} certificates after reset`);
        }
      }
    }
    
    console.log('Certificate filtering test completed!');
    return true;
  } else {
    console.log('Certificate filter form not found, skipping test');
    return false;
  }
}

// Run the tests
runCertificateTests().catch(error => {
  console.error(`Error running tests: ${error.message}`);
  process.exit(1);
});