import { test, expect } from '@playwright/test';
import { CertificatePage } from './pages/CertificatePage';
import { DashboardPage } from './pages/DashboardPage';
import { LoginPage } from './pages/LoginPage';
import { CertificateTestData } from './utils/CertificateTestData';
import { Config } from './utils/Config';

// Certificate Management Tests
test('Certificate management functionality', async ({ page, browser }) => {
  // Set up test data and generate certificates first
  console.log('Setting up test data for certificate management tests...');
  
  // Create a new browser context for data setup
  const context = await browser.newContext();
  const setupPage = await context.newPage();
  
  // Set up the test data
  const testData = new CertificateTestData(setupPage);
  await testData.loginAsTrainer();
  
  // Create a test event with attendees
  const eventName = await testData.setupCertificateTestEvent();
  expect(eventName).not.toBeNull();
  
  // Navigate to Generate Certificates page
  const setupCertPage = new CertificatePage(setupPage);
  await setupCertPage.navigateToGenerateCertificates();
  
  // Select the event and generate certificates for all attendees
  await setupCertPage.selectEvent(eventName as string);
  await setupCertPage.selectAllAttendees();
  await setupCertPage.generateCertificates();
  
  // Close the setup context
  await context.close();
  
  // Start the actual test
  console.log('Step 1: Logging in...');
  const loginPage = new LoginPage(page);
  await loginPage.navigate();
  await loginPage.login(Config.testTrainer.username, Config.testTrainer.password);
  
  console.log('Step 2: Navigate to dashboard...');
  const dashboardPage = new DashboardPage(page);
  await dashboardPage.navigate();
  
  console.log('Step 3: Navigate to Certificate Reports...');
  await dashboardPage.clickCertificateReports();
  
  console.log('Step 4: Test certificate management functionality...');
  const certificatePage = new CertificatePage(page);
  
  try {
    // Verify we're on the certificate reports page
    const pageVisible = await certificatePage.isCertificateReportsPageVisible();
    expect(pageVisible).toBeTruthy();
    
    // Search for certificates from our test event
    await certificatePage.searchCertificates(eventName as string);
    
    // Verify certificates exist
    const certificateCount = await certificatePage.getCertificateCount();
    console.log(`Found ${certificateCount} certificates for the test event`);
    expect(certificateCount).toBeGreaterThan(0);
    
    if (certificateCount > 0) {
      // Test viewing a certificate
      console.log('Step 4a: Testing certificate viewing...');
      await certificatePage.viewCertificate(0);
      await certificatePage.closePreview();
      
      // Test emailing a certificate
      console.log('Step 4b: Testing certificate emailing...');
      try {
        await certificatePage.emailCertificate(0);
        // Check for success message
        const hasSuccessMessage = await certificatePage.isSuccessMessageVisible();
        if (hasSuccessMessage) {
          const successMessage = await certificatePage.getSuccessMessage();
          console.log(`Email success message: ${successMessage}`);
        }
      } catch (error) {
        console.log(`Email functionality unavailable or failed: ${error.message}`);
        // Continue with the test - email might not be implemented
      }
      
      // Test revoking a certificate if we have more than one
      if (certificateCount > 1) {
        console.log('Step 4c: Testing certificate revocation...');
        await certificatePage.revokeCertificate(1);
        
        // Refresh the page to see the updated status
        await certificatePage.navigateToCertificateReports();
        await certificatePage.searchCertificates(eventName as string);
        
        // The second certificate should now be revoked
        // Add verification if the UI exposes revocation status
      }
      
      // Test pagination if available
      console.log('Step 4d: Testing pagination if available...');
      const hasPagination = await certificatePage.isPaginationVisible();
      if (hasPagination) {
        console.log('Pagination is available, testing navigation...');
        // Try to navigate to next page
        const couldGoNext = await certificatePage.goToNextPage();
        if (couldGoNext) {
          // Go back to previous page
          await certificatePage.goToPreviousPage();
        }
      } else {
        console.log('Pagination not available (not enough certificates)');
      }
    }
  } catch (error) {
    console.error('Error during certificate management test:', error.message);
    // Take a screenshot for debugging
    await page.screenshot({ path: `${Config.screenshotPath}/error-certificate-management.png` });
    throw error;
  }
  
  console.log('Certificate management test completed successfully');
});