import { STAGING_URL, PATHS, TIMEOUTS } from './config/staging-config';
import { test, expect } from '@playwright/test';

/**
 * Test to verify certificate test data is showing correctly
 * 
 * Checks the certificate reports page to ensure all test data is visible and filterable
 */
test.describe('Certificate Test Data Verification', () => {
  const baseUrl = process.env.BASE_URL || 'https://upskill-staging.measurequick.com';
  const adminUsername = process.env.ADMIN_USERNAME || 'admin';
  const adminPassword = process.env.ADMIN_PASSWORD || 'password';
  const certificateReportsUrl = `${baseUrl}/certificate-reports/`;
  
  test.beforeEach(async ({ page }) => {
    // Login before each test
    await page.goto(`${baseUrl}/wp-login.php`);
    await page.waitForSelector('#user_login');
    await page.fill('#user_login', adminUsername);
    await page.fill('#user_pass', adminPassword);
    await page.click('#wp-submit');
    await page.waitForURL(/wp-admin/);
    
    // Navigate to certificate reports page
    await page.goto(certificateReportsUrl);
    await page.waitForSelector('.hvac-certificate-reports');
  });
  
  test('Verify certificate count matches expected', async ({ page }) => {
    // Get the total count displayed on the page
    await page.waitForSelector('.hvac-total-count');
    const totalCountText = await page.textContent('.hvac-total-count');
    
    // Extract the number from text like "Showing 1-20 of 54 certificates"
    const totalMatch = totalCountText?.match(/of (\d+) certificates/);
    const totalCount = totalMatch ? parseInt(totalMatch[1]) : 0;
    
    // We expect at least 47 certificates (from our test data creation script)
    // But there might be more if other test data exists
    expect(totalCount).toBeGreaterThanOrEqual(47);
    console.log(`Found total of ${totalCount} certificates`);
  });
  
  test('Verify event filtering works', async ({ page }) => {
    // Clear any existing filters first
    if (await page.$('a.hvac-clear-filters')) {
      await page.click('a.hvac-clear-filters');
      await page.waitForTimeout(500);
    }
    
    // Select one of our test events
    await page.waitForSelector('#filter_event');
    await page.selectOption('#filter_event', { label: 'HVAC System Design Fundamentals' });
    await page.click('button[type="submit"]');
    
    // Wait for page to refresh with filtered results
    await page.waitForSelector('.hvac-certificate-table');
    await page.waitForSelector('.hvac-total-count');
    
    // Check the count text shows some results
    const eventFilteredCountText = await page.textContent('.hvac-total-count');
    const countMatch = eventFilteredCountText?.match(/of (\d+) certificates/);
    const filteredCount = countMatch ? parseInt(countMatch[1]) : 0;
    
    // We should have around 20 certificates for this event
    expect(filteredCount).toBeGreaterThanOrEqual(15);
    expect(filteredCount).toBeLessThanOrEqual(25);
    console.log(`Found ${filteredCount} certificates for HVAC System Design Fundamentals`);
    
    // Check that the event name column contains the correct name
    const eventNameCells = await page.$$eval('td.certificate-event', cells => 
      cells.map(cell => cell.textContent?.trim())
    );
    
    // All event cells should contain the filtered event name
    for (const cellText of eventNameCells) {
      expect(cellText).toContain('HVAC System Design Fundamentals');
    }
  });
  
  test('Verify attendee filtering works', async ({ page }) => {
    // Clear any existing filters first
    if (await page.$('a.hvac-clear-filters')) {
      await page.click('a.hvac-clear-filters');
      await page.waitForTimeout(500);
    }
    
    // Search for Ben Tester (which should be in our test data)
    await page.waitForSelector('#search_attendee');
    await page.fill('#search_attendee', 'Ben Tester');
    await page.click('button[type="submit"]');
    
    // Wait for page to refresh with filtered results
    await page.waitForSelector('.hvac-certificate-table');
    
    // Check that we have at least some results (Ben Tester appears in multiple events)
    const benFilteredCountText = await page.textContent('.hvac-total-count');
    const benCountMatch = benFilteredCountText?.match(/of (\d+) certificates/);
    const benFilteredCount = benCountMatch ? parseInt(benCountMatch[1]) : 0;
    
    // We should have at least 1 certificate for Ben Tester
    expect(benFilteredCount).toBeGreaterThanOrEqual(1);
    console.log(`Found ${benFilteredCount} certificates for Ben Tester`);
    
    // Check the attendee column contains the searched name
    const attendeeNameCells = await page.$$eval('td.certificate-attendee', cells => 
      cells.map(cell => cell.textContent?.trim())
    );
    
    // All attendee cells should contain the filtered name
    for (const cellText of attendeeNameCells) {
      expect(cellText?.toLowerCase()).toContain('ben tester');
    }
    
    // Clear filters again
    await page.click('a.hvac-clear-filters');
    await page.waitForTimeout(500);
    
    // Test email search
    await page.fill('#search_attendee', 'ben@tealmaker.com');
    await page.click('button[type="submit"]');
    
    // Wait for results
    await page.waitForSelector('.hvac-certificate-table');
    
    // Check results
    const emailFilteredCountText = await page.textContent('.hvac-total-count');
    const emailCountMatch = emailFilteredCountText?.match(/of (\d+) certificates/);
    const emailFilteredCount = emailCountMatch ? parseInt(emailCountMatch[1]) : 0;
    
    // We should have at least 1 certificate for ben@tealmaker.com
    expect(emailFilteredCount).toBeGreaterThanOrEqual(1);
    console.log(`Found ${emailFilteredCount} certificates for ben@tealmaker.com`);
  });
  
  test('Verify revocation status filtering works', async ({ page }) => {
    // Clear any existing filters first
    if (await page.$('a.hvac-clear-filters')) {
      await page.click('a.hvac-clear-filters');
      await page.waitForTimeout(500);
    }
    
    // Filter by revoked certificates
    await page.waitForSelector('#filter_revoked');
    await page.selectOption('#filter_revoked', { value: '1' });
    await page.click('button[type="submit"]');
    
    // Wait for page to refresh with filtered results
    await page.waitForSelector('.hvac-certificate-table');
    
    // Check the count text shows some results
    const revokedCountText = await page.textContent('.hvac-total-count');
    const revokedMatch = revokedCountText?.match(/of (\d+) certificates/);
    const revokedCount = revokedMatch ? parseInt(revokedMatch[1]) : 0;
    
    // We should have around 5 revoked certificates
    expect(revokedCount).toBeGreaterThanOrEqual(1);
    console.log(`Found ${revokedCount} revoked certificates`);
    
    // Check the status column shows revoked
    const statusCells = await page.$$eval('td.certificate-status', cells => 
      cells.map(cell => cell.textContent?.trim())
    );
    
    // All status cells should show revoked
    for (const cellText of statusCells) {
      expect(cellText?.toLowerCase()).toContain('revoked');
    }
  });
  
  test('Verify complex filter combinations work', async ({ page }) => {
    // Clear any existing filters first
    if (await page.$('a.hvac-clear-filters')) {
      await page.click('a.hvac-clear-filters');
      await page.waitForTimeout(500);
    }
    
    // Apply multiple filters - event + attendee search
    await page.waitForSelector('#filter_event');
    await page.selectOption('#filter_event', { label: 'Advanced Refrigeration Technology' });
    await page.fill('#search_attendee', 'tester');
    await page.click('button[type="submit"]');
    
    // Wait for page to refresh with filtered results
    await page.waitForSelector('.hvac-certificate-table');
    
    // Check if we have results that match both criteria
    const combinedFilterText = await page.textContent('.hvac-total-count');
    console.log(`Combined filter results: ${combinedFilterText}`);
    
    // Get table cells to verify content
    const eventCells = await page.$$eval('td.certificate-event', cells => 
      cells.map(cell => cell.textContent?.trim())
    );
    
    const attendeeCells = await page.$$eval('td.certificate-attendee', cells => 
      cells.map(cell => cell.textContent?.trim())
    );
    
    // Check a sample of cells to make sure they match our criteria
    if (eventCells.length > 0) {
      expect(eventCells[0]).toContain('Advanced Refrigeration Technology');
    }
    
    if (attendeeCells.length > 0) {
      expect(attendeeCells[0]?.toLowerCase()).toContain('tester');
    }
  });
  
  test('Verify pagination works with large dataset', async ({ page }) => {
    // Clear any existing filters first
    if (await page.$('a.hvac-clear-filters')) {
      await page.click('a.hvac-clear-filters');
      await page.waitForTimeout(500);
    }
    
    // Check if pagination is present
    const hasPagination = await page.$('.hvac-pagination');
    
    if (hasPagination) {
      // Get current page number
      const currentPage = await page.$eval('.hvac-pagination .current', el => el.textContent?.trim());
      console.log(`Current page: ${currentPage}`);
      
      // Check if there's a next page link
      const hasNextPage = await page.$('.hvac-pagination a.next');
      
      if (hasNextPage) {
        // Click next page
        await page.click('.hvac-pagination a.next');
        await page.waitForSelector('.hvac-certificate-table');
        
        // Verify we're on a different page
        const newPage = await page.$eval('.hvac-pagination .current', el => el.textContent?.trim());
        console.log(`New page: ${newPage}`);
        
        expect(newPage).not.toEqual(currentPage);
      } else {
        console.log('No next page link found - dataset may be too small for pagination');
      }
    } else {
      console.log('No pagination found - dataset may be too small for pagination');
    }
  });
});