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';

test.describe('Certificate Generation Tests', () => {
  test('should handle certificate generation for non-checked-in attendees', async ({ page, browser }) => {
    // Set up test data
    console.log('Setting up test data for non-checked-in certificate 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 (some checked-in, some not)
    const eventName = await testData.setupCertificateTestEvent();
    expect(eventName).not.toBeNull();
    
    // Close the setup context
    await context.close();
    
    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 Generate Certificates...');
    await dashboardPage.clickGenerateCertificates();
    
    console.log('Step 4: Generate certificates for non-checked-in attendees...');
    const certificatePage = new CertificatePage(page);
    
    // Verify we're on the generate certificates page
    const pageVisible = await certificatePage.isGenerateCertificatesPageVisible();
    expect(pageVisible).toBeTruthy();
    
    // Select the test event
    await certificatePage.selectEvent(eventName as string);

    // Get attendee counts
    const totalAttendees = await certificatePage.getAttendeeCount();
    const checkedInAttendees = await certificatePage.getCheckedInAttendeeCount();
    const nonCheckedInAttendees = totalAttendees - checkedInAttendees;
    
    console.log(`Found ${totalAttendees} total attendees, ${nonCheckedInAttendees} non-checked-in`);
    expect(totalAttendees).toBeGreaterThan(0);
    expect(nonCheckedInAttendees).toBeGreaterThan(0);
    
    // Select only non-checked-in attendees
    await certificatePage.selectNonCheckedInAttendees();
    
    // Generate certificates
    await certificatePage.generateCertificates();
    
    // This test can have two possible outcomes based on implementation:
    // 1. The system allows certificates for non-checked-in attendees
    // 2. The system prevents certificates for non-checked-in attendees
    
    try {
      // Check if there's an error message
      const hasError = await certificatePage.isErrorMessageVisible();
      const hasSuccess = await certificatePage.isSuccessMessageVisible();
      
      if (hasError) {
        // Case 2: System prevents certificates for non-checked-in attendees
        console.log('System prevents certificate generation for non-checked-in attendees');
        const errorMessage = await certificatePage.getErrorMessage();
        console.log(`Error message: ${errorMessage}`);
        expect(errorMessage).toContain('checked-in');
      } else if (hasSuccess) {
        // Case 1: System allows certificates for non-checked-in attendees
        console.log('System allows certificate generation for non-checked-in attendees');
        const successMessage = await certificatePage.getSuccessMessage();
        console.log(`Success message: ${successMessage}`);
        
        // Navigate to certificate reports to verify
        await dashboardPage.navigate();
        await dashboardPage.clickCertificateReports();
        
        // Filter certificates for the test event
        await certificatePage.searchCertificates(eventName as string);
        
        // Check certificate count - should include the non-checked-in attendees
        const certificateCount = await certificatePage.getCertificateCount();
        console.log(`Found ${certificateCount} certificates for event (should include non-checked-in)`);
        expect(certificateCount).toBeGreaterThanOrEqual(nonCheckedInAttendees);
      } else {
        // Unexpected case - neither success nor error
        throw new Error('Neither success nor error message was displayed after certificate generation');
      }
    } catch (error) {
      console.error('Error during certificate generation test:', error.message);
      // Take a screenshot for debugging
      await page.screenshot({ path: `${Config.screenshotPath}/error-non-checked-in-test.png` });
      throw error;
    }
    
    console.log('Certificate generation test for non-checked-in attendees completed successfully');
  });
});