import { test, expect } from '@playwright/test';

/**
 * Certificate Generation End-to-End Test
 * 
 * This test verifies the certificate generation functionality:
 * - Login as a trainer
 * - Navigate to an event summary page
 * - Generate certificates for attendees
 * - View certificate
 * - Email certificate to a test email
 * - Revoke certificate
 */

test.describe('Certificate Generation Tests', () => {
  const stagingUrl = 'https://wordpress-974670-5399585.cloudwaysapps.com/';
  const loginUrl = `${stagingUrl}community-login/`;
  const dashboardUrl = `${stagingUrl}hvac-dashboard/`;
  const testEmail = 'ben@tealmaker.com';
  
  test.beforeEach(async ({ page }) => {
    // Login as trainer
    await page.goto(loginUrl);
    await page.fill('input[name="log"]', 'test_trainer');
    await page.fill('input[name="pwd"]', 'Test123!');
    await page.click('input[type="submit"]');
    
    // Verify login was successful by checking for dashboard
    await expect(page).toHaveURL(dashboardUrl);
  });
  
  test('Generate and manage certificates for an event', async ({ page }) => {
    // Navigate to the dashboard to find an event
    await page.goto(dashboardUrl);
    
    // Click on the first event summary link
    await page.click('.hvac-event-title a');
    
    // Wait for the event summary page to load
    await expect(page.locator('h1')).toContainText('Summary');
    
    // Check if we have attendees
    const hasAttendees = await page.locator('.hvac-transactions-table').isVisible();
    
    if (hasAttendees) {
      // Check if any attendee doesn't have a certificate yet
      const generateButtonExists = await page.locator('.hvac-cert-action:text("Generate")').isVisible();
      
      if (generateButtonExists) {
        // Generate a certificate for an attendee
        await page.click('.hvac-cert-action:text("Generate")');
        
        // Navigate to the generate certificates page
        await expect(page.locator('h1')).toContainText('Generate Certificates');
        
        // Check the 'checked_in_only' checkbox
        await page.check('#checked-in-only-checkbox');
        
        // Generate certificates
        await page.click('button[type="submit"]');
        
        // Wait for success message
        await expect(page.locator('.hvac-success-message')).toBeVisible();
        
        // Go back to the event summary
        await page.click('a:text("Back to Event Summary")');
      }
      
      // Check if there are any generated certificates
      const viewButtonExists = await page.locator('.hvac-cert-action:text("View")').isVisible();
      
      if (viewButtonExists) {
        // View a certificate
        await page.click('.hvac-cert-action:text("View")', { force: true });
        
        // Wait for the certificate modal to appear
        await expect(page.locator('#hvac-certificate-modal')).toBeVisible();
        
        // Wait for the certificate iframe to load
        await page.waitForSelector('#hvac-certificate-preview[src^="http"]');
        
        // Close the modal
        await page.click('.hvac-modal-close');
        
        // Email a certificate
        await page.click('.hvac-cert-action:text("Email")', { force: true });
        
        // Confirm the email dialog
        await page.once('dialog', dialog => dialog.accept());
        
        // Wait for success message
        await page.waitForTimeout(2000); // Wait for alert to appear and dismiss
        
        // Revoke a certificate
        await page.click('.hvac-cert-action:text("Revoke")', { force: true });
        
        // Enter reason in the prompt
        await page.once('dialog', dialog => dialog.accept('Revocation test'));
        
        // Wait for status to update to Revoked
        await expect(page.locator('td:has-text("Revoked")')).toBeVisible();
      } else {
        console.log('No generated certificates available to test with');
      }
    } else {
      console.log('No attendees found for the event');
    }
  });
  
  test('Navigate to Certificate Reports page', async ({ page }) => {
    // Navigate to certificate reports page
    await page.goto(`${stagingUrl}certificate-reports/`);
    
    // Verify the page loaded successfully
    await expect(page.locator('h1')).toContainText('Certificate Reports');
    
    // Try filtering certificates
    await page.selectOption('select[name="filter_status"]', 'all');
    await page.click('button[type="submit"]');
    
    // Check for certificate data or empty message
    const hasReports = await page.locator('.hvac-certificate-table').isVisible();
    if (!hasReports) {
      await expect(page.locator('.hvac-no-certificates')).toBeVisible();
    }
  });
});