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

/**
 * Certificate Tests
 * 
 * These tests verify the certificate generation, reporting, and filtering functionality
 * 
 * @group @certificate
 */

// STAGING_URL is now imported from config

// Test data for existing certificates to verify
const TEST_EVENTS = [
  { id: '5641', name: 'HVAC System Design Fundamentals' }, 
  { id: '5668', name: 'Advanced Refrigeration Technology' },
  { id: '5688', name: 'Building Automation Systems Workshop' }
];

// Test data for attendee filtering
const TEST_ATTENDEES = [
  { name: 'John Smith', email: 'john.smith@example.com' },
  { name: 'Sarah Johnson', email: 'sarah.johnson@example.com' },
  { name: 'Michael Brown', email: 'michael.brown@example.com' }
];

// Common setup for tests
async function setupTest(page) {
  const loginPage = new LoginPage(page);
  await loginPage.navigate();
  await loginPage.login('test_trainer', 'Test123!');
  
  // Verify login
  const dashboardPage = new DashboardPage(page);
  await expect(page).toHaveURL(/hvac-dashboard/);
  
  return { loginPage, dashboardPage };
}

test.describe('Certificate Generation and Reports', () => {
  test('Navigate to certificate generation page', async ({ page }) => {
    const { dashboardPage } = await setupTest(page);
    
    // Navigate to Generate Certificates page
    await dashboardPage.clickGenerateCertificates();
    
    // Verify page components
    const certificatePage = new CertificatePage(page);
    const pageVisible = await certificatePage.isGenerateCertificatesPageVisible();
    expect(pageVisible).toBeTruthy();
    
    // Check for event dropdown
    await expect(page.locator('#event_id')).toBeVisible();
  });
  
  test('Navigate to certificate reports page', async ({ page }) => {
    const { dashboardPage } = await setupTest(page);
    
    // Navigate to Certificate Reports page
    await dashboardPage.clickCertificateReports();
    
    // Verify page components
    const certificatePage = new CertificatePage(page);
    const pageVisible = await certificatePage.isCertificateReportsPageVisible();
    expect(pageVisible).toBeTruthy();
    
    // Check for filter form
    await expect(page.locator('form.hvac-certificate-filters')).toBeVisible();
  });
  
  test('Filter certificates by event', async ({ page }) => {
    const { dashboardPage } = await setupTest(page);
    
    // Navigate to Certificate Reports page
    await dashboardPage.clickCertificateReports();
    const certificatePage = new CertificatePage(page);
    
    // Select an event to filter
    const testEvent = TEST_EVENTS[0];
    await certificatePage.searchCertificates(testEvent.name);
    
    // Verify results
    await page.waitForLoadState('networkidle');
    const certificateCount = await certificatePage.getCertificateCount();
    console.log(`Found ${certificateCount} certificates for event: ${testEvent.name}`);
    
    // Should have at least some certificates (can be zero if no certificates exist)
    expect(certificateCount).toBeGreaterThanOrEqual(0);
  });
  
  test('Search certificates by attendee', async ({ page }) => {
    const { dashboardPage } = await setupTest(page);
    
    // Navigate to Certificate Reports page
    await dashboardPage.clickCertificateReports();
    const certificatePage = new CertificatePage(page);
    
    // Search for an attendee
    const testAttendee = TEST_ATTENDEES[0];
    await certificatePage.searchAttendee(testAttendee.name);
    
    // Verify search results
    await page.waitForLoadState('networkidle');
    const certificateCount = await certificatePage.getCertificateCount();
    console.log(`Found ${certificateCount} certificates for attendee: ${testAttendee.name}`);
    
    // Verify filter was applied (search input should have the attendee name)
    const searchValue = await page.inputValue('#search_attendee');
    expect(searchValue).toEqual(testAttendee.name);
  });
  
  test('Reset certificate filters', async ({ page }) => {
    const { dashboardPage } = await setupTest(page);
    
    // Navigate to Certificate Reports page
    await dashboardPage.clickCertificateReports();
    const certificatePage = new CertificatePage(page);
    
    // Apply a filter first
    await certificatePage.searchAttendee('test');
    
    // Get count with filter
    const filteredCount = await certificatePage.getCertificateCount();
    
    // Reset filters
    await certificatePage.resetFilters();
    
    // Get count after reset
    const resetCount = await certificatePage.getCertificateCount();
    
    // The search input should be empty after reset
    const searchValue = await page.inputValue('#search_attendee');
    expect(searchValue).toEqual('');
    
    console.log(`Filtered certificates: ${filteredCount}, After reset: ${resetCount}`);
    // We can't guarantee counts will differ, but the reset should work
  });
  
  test('View certificate details', async ({ page }) => {
    const { dashboardPage } = await setupTest(page);
    
    // Navigate to Certificate Reports page
    await dashboardPage.clickCertificateReports();
    const certificatePage = new CertificatePage(page);
    
    // Get initial certificate count
    const certificateCount = await certificatePage.getCertificateCount();
    console.log(`Found ${certificateCount} certificates`);
    
    // Skip test if no certificates
    test.skip(certificateCount === 0, 'No certificates available to view');
    
    if (certificateCount > 0) {
      // View the first certificate
      await certificatePage.viewCertificate(0);
      
      // Verify preview is visible
      await expect(page.locator('.hvac-certificate-preview')).toBeVisible();
      
      // Close the preview
      await certificatePage.closePreview();
      
      // Preview should be hidden
      await expect(page.locator('.hvac-certificate-preview')).not.toBeVisible();
    }
  });
});

// Comprehensive test for attendee search functionality
test('Attendee search functionality', async ({ page }) => {
  const { dashboardPage } = await setupTest(page);
  
  // Navigate to Certificate Reports page
  await dashboardPage.clickCertificateReports();
  const certificatePage = new CertificatePage(page);
  
  // Test partial name search
  await certificatePage.searchAttendee('John');
  await page.waitForLoadState('networkidle');
  
  // Verify search results
  const nameSearchCount = await certificatePage.getCertificateCount();
  console.log(`Found ${nameSearchCount} certificates for attendee name: John`);
  
  // Reset filters
  await certificatePage.resetFilters();
  
  // Test email domain search
  await certificatePage.searchAttendee('example.com');
  await page.waitForLoadState('networkidle');
  
  // Verify search results
  const emailSearchCount = await certificatePage.getCertificateCount();
  console.log(`Found ${emailSearchCount} certificates for email domain: example.com`);
  
  // Reset filters
  await certificatePage.resetFilters();
  
  // Test combination of filters (event + attendee)
  if (TEST_EVENTS.length > 0) {
    const testEvent = TEST_EVENTS[0];
    
    // Select an event
    await certificatePage.searchCertificates(testEvent.name);
    
    // Then search for an attendee
    await certificatePage.searchAttendee('test');
    
    // Verify combined results
    const combinedCount = await certificatePage.getCertificateCount();
    console.log(`Found ${combinedCount} certificates for event "${testEvent.name}" and attendee "test"`);
    
    // Verify both filters were applied
    const searchValue = await page.inputValue('#search_attendee');
    expect(searchValue).toEqual('test');
    
    // Reset filters
    await certificatePage.resetFilters();
  }
});