import { test, expect } from './fixtures/auth';
import { CommonActions } from './utils/common-actions';

/**
 * Optimized certificate tests with better performance and reliability
 * @tag @certificates @optimized
 */

test.describe('Certificate System - Optimized', () => {
  test('Certificate Reports functionality', async ({ authenticatedPage: page }) => {
    test.setTimeout(20000);
    const actions = new CommonActions(page);
    
    // Navigate to Certificate Reports
    await actions.navigateAndWait('/certificate-reports/');
    await actions.screenshot('certificate-reports-page');
    
    // Verify page loaded
    await expect(page.locator('h1, h2').filter({ hasText: /certificate/i }).first()).toBeVisible();
    
    // Verify navigation
    await actions.verifyNavigation();
    
    // Check for any statistics (flexible)
    const possibleStats = [
      page.locator('.stat-value'),
      page.locator('.stat-number'), 
      page.locator('.dashboard-stat'),
      page.locator('td:has-text(/^\\d+$/)'),
      page.locator('span:has-text(/^\\d+$/)')
    ];
    
    let statsFound = 0;
    for (const statLocator of possibleStats) {
      const count = await statLocator.count();
      statsFound += count;
    }
    
    console.log(`Found ${statsFound} potential statistics elements`);
    await actions.screenshot('certificate-reports-verified');
  });

  test('Generate Certificates page functionality', async ({ authenticatedPage: page }) => {
    test.setTimeout(25000);
    const actions = new CommonActions(page);
    
    // Navigate to Generate Certificates
    await actions.navigateAndWait('/generate-certificates/');
    await actions.screenshot('generate-certificates-page');
    
    // Verify page loaded
    await expect(page.locator('h1, h2').filter({ hasText: /generate/i }).first()).toBeVisible();
    
    // Verify navigation
    await actions.verifyNavigation();
    
    // Test event selection
    const eventSelect = page.locator('select[name="event_id"]');
    await expect(eventSelect).toBeVisible();
    
    const eventOptions = await eventSelect.locator('option').count();
    console.log(`Found ${eventOptions} event options`);
    expect(eventOptions).toBeGreaterThan(0);
    
    // Test event selection if options available
    if (eventOptions > 1) {
      console.log('Testing event selection...');
      await eventSelect.selectOption({ index: 1 });
      await actions.waitForComplexAjax();
      
      // Check for any form elements that might have loaded
      const formElements = await page.locator('input, button, select').count();
      console.log(`Found ${formElements} form elements after event selection`);
      
      await actions.screenshot('event-selected');
    }
    
    console.log('✓ Generate Certificates functionality verified');
  });

  test('Certificate navigation flow', async ({ authenticatedPage: page }) => {
    test.setTimeout(30000);
    const actions = new CommonActions(page);
    
    // Start at Certificate Reports
    await actions.navigateAndWait('/certificate-reports/');
    await expect(page.locator('h1, h2').filter({ hasText: /certificate.*report/i }).first()).toBeVisible();
    
    // Navigate to Generate Certificates
    await page.click('text=Generate Certificates');
    await actions.waitForAjax();
    await expect(page.locator('h1, h2').filter({ hasText: /generate/i }).first()).toBeVisible();
    
    // Navigate back to Reports via text link
    const reportLinks = await page.locator('text=Certificate Reports').count();
    if (reportLinks > 0) {
      await page.click('text=Certificate Reports');
      await actions.waitForAjax();
      await expect(page.locator('h1, h2').filter({ hasText: /certificate.*report/i }).first()).toBeVisible();
    }
    
    // Return to dashboard
    await page.click('a[href*="hvac-dashboard"]');
    await actions.waitForAjax();
    await expect(page).toHaveURL(/hvac-dashboard/);
    
    console.log('✓ Certificate navigation flow verified');
  });

  test('Certificate system error monitoring', async ({ authenticatedPage: page }) => {
    test.setTimeout(25000);
    const actions = new CommonActions(page);
    const errors = [];
    
    // Monitor for errors
    page.on('console', (msg) => {
      if (msg.type() === 'error') {
        errors.push(msg.text());
      }
    });
    
    page.on('pageerror', (error) => {
      errors.push(error.message);
    });
    
    // Test certificate pages for errors
    const certificatePages = [
      '/certificate-reports/',
      '/generate-certificates/'
    ];
    
    for (const certPage of certificatePages) {
      console.log(`Testing ${certPage} for errors...`);
      await actions.navigateAndWait(certPage);
      
      // Verify page loaded
      const hasContent = await page.locator('h1, h2, .content, main').count() > 0;
      expect(hasContent).toBeTruthy();
      
      // Wait for any delayed errors
      await page.waitForTimeout(2000);
    }
    
    // Check for any JavaScript/PHP errors
    const phpErrors = errors.filter(error => error.includes('PHP') || error.includes('Fatal'));
    const jsErrors = errors.filter(error => !error.includes('favicon') && !error.includes('net::ERR'));
    
    console.log(`Found ${phpErrors.length} PHP errors, ${jsErrors.length} JS errors`);
    
    // Log errors for debugging but don't fail the test unless they're critical
    if (phpErrors.length > 0) {
      console.log('PHP errors detected:', phpErrors);
    }
    if (jsErrors.length > 0) {
      console.log('JS errors detected:', jsErrors);
    }
    
    // Only fail on PHP errors (these are critical)
    expect(phpErrors.length).toBe(0);
    
    console.log('✓ Certificate system error monitoring completed');
  });
});