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

const STAGING_URL = 'https://wordpress-974670-5399585.cloudwaysapps.com';

/**
 * Certificate Generation Tests for Checked-In Attendees
 * @group @certificate
 */
test('Generate certificates for checked-in attendees', async ({ page, browser }) => {
  // Setup test data
  console.log('Setting up test data for 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();
  
  console.log(`Test event created: ${eventName}`);
  
  // Close the setup context
  await context.close();
  
  console.log('Step 1: Logging in...');
  await page.goto(`${STAGING_URL}/community-login/`);
  await page.fill('#user_login', 'test_trainer');
  await page.fill('#user_pass', 'Test123!');
  await page.click('#wp-submit');
  await page.waitForLoadState('networkidle');
  await expect(page).toHaveURL(/hvac-dashboard/);
  
  console.log('Step 2: Navigate to dashboard...');
  const dashboardPage = new DashboardPage(page);
  await dashboardPage.navigate();
  
  console.log('Step 3: Verify certificate links are visible...');
  await dashboardPage.clickGenerateCertificates();
  
  console.log('Step 4: Generate certificates for checked-in attendees only...');
  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();
  
  console.log(`Found ${totalAttendees} total attendees, ${checkedInAttendees} checked-in`);
  expect(totalAttendees).toBeGreaterThan(0);
  expect(checkedInAttendees).toBeGreaterThan(0);
  
  // Select only checked-in attendees
  await certificatePage.selectCheckedInAttendees();
  
  // Generate certificates
  await certificatePage.generateCertificates();
  
  // Verify success message
  const success = await certificatePage.isSuccessMessageVisible();
  expect(success).toBeTruthy();
  
  const successMessage = await certificatePage.getSuccessMessage();
  console.log(`Success message: ${successMessage}`);
  expect(successMessage).toContain("success");
  
  console.log('Step 5: Verify certificates in Certificate Reports...');
  
  // Navigate to certificate reports
  await dashboardPage.navigate();
  await dashboardPage.clickCertificateReports();
  
  // Verify we're on the certificate reports page
  const reportsPageVisible = await certificatePage.isCertificateReportsPageVisible();
  expect(reportsPageVisible).toBeTruthy();
  
  // Filter certificates for the test event
  await certificatePage.searchCertificates(eventName as string);
  
  // Check certificate count
  const certificateCount = await certificatePage.getCertificateCount();
  console.log(`Found ${certificateCount} certificates for event`);
  
  // We should have certificates equal to the number of checked-in attendees
  // Note: This assumes that the test data setup created at least one checked-in attendee
  expect(certificateCount).toBeGreaterThan(0);
  
  // View a certificate
  if (certificateCount > 0) {
    await certificatePage.viewCertificate(0);
    
    // Close the preview
    await certificatePage.closePreview();
  }
  
  console.log('Certificate generation test for checked-in attendees completed successfully');
});