import { test, expect } from '@playwright/test';
import { CommonActions } from './utils/common-actions';

/**
 * Master Dashboard test using master_trainer user
 */

test.describe('Master Dashboard Master Trainer Access', () => {
  
  test('Master Trainer user can access Master Dashboard', async ({ page }) => {
    test.setTimeout(60000);
    const actions = new CommonActions(page);
    
    // Navigate to community login page
    await page.goto('https://upskill-staging.measurequick.com/community-login/');
    await page.waitForLoadState('networkidle');
    
    // Login as master_trainer
    await page.fill('#user_login', 'master_trainer');
    await page.fill('#user_pass', 'MasterTrainer#2025!');
    await page.click('#wp-submit');
    
    // Wait for login to complete
    await page.waitForLoadState('networkidle');
    
    // Check if login was successful
    const afterLoginUrl = page.url();
    console.log('URL after master trainer login:', afterLoginUrl);
    
    if (afterLoginUrl.includes('hvac-dashboard')) {
      console.log('✓ Successfully logged in as master_trainer');
      
      // Navigate directly to master dashboard
      await page.goto('https://upskill-staging.measurequick.com/master-dashboard/');
      await page.waitForLoadState('networkidle');
      
      // Take screenshot
      await page.screenshot({ 
        path: `test-results/screenshots/master-dashboard-master-trainer-${Date.now()}.png`,
        fullPage: true 
      });
      
      // Check final URL
      const masterDashUrl = page.url();
      console.log('Master Dashboard URL:', masterDashUrl);
      
      // Check page content
      const pageTitle = await page.title();
      console.log('Page title:', pageTitle);
      
      // Look for dashboard elements
      const h1Count = await page.locator('h1').count();
      console.log('H1 elements found:', h1Count);
      
      if (h1Count > 0) {
        const h1Text = await page.locator('h1').first().textContent();
        console.log('H1 text:', h1Text);
        
        // Check what we see
        if (h1Text?.includes('Master Dashboard')) {
          console.log('✓ Master Dashboard rendered successfully for master_trainer!');
          
          // Verify we see the same data as admin
          const totalEvents = await page.locator('.hvac-stat-card:has-text("Total Events") p').first().textContent();
          console.log('Total Events shown:', totalEvents);
          
          const activeTrainers = await page.locator('.hvac-stat-card:has-text("Active Trainers") p').first().textContent();
          console.log('Active Trainers shown:', activeTrainers);
          
          const totalRevenue = await page.locator('.hvac-stat-card:has-text("Total Revenue") p').first().textContent();
          console.log('Total Revenue shown:', totalRevenue);
          
          // Success!
          expect(h1Text).toContain('Master Dashboard');
          expect(page.url()).toContain('master-dashboard');
          
        } else if (h1Text?.includes('Access Denied')) {
          console.log('✗ Access Denied - master_trainer does not have permission');
          console.log('This suggests the role permissions need to be checked');
        } else {
          console.log('✗ Unexpected page content:', h1Text);
        }
      }
    } else {
      console.log('✗ Master trainer login failed or redirected elsewhere');
    }
  });
  
  test('Regular trainer cannot access Master Dashboard', async ({ page }) => {
    test.setTimeout(30000);
    const actions = new CommonActions(page);
    
    // Navigate to community login page
    await page.goto('https://upskill-staging.measurequick.com/community-login/');
    await page.waitForLoadState('networkidle');
    
    // Login as regular test_trainer
    await page.fill('#user_login', 'test_trainer');
    await page.fill('#user_pass', 'Test123!');
    await page.click('#wp-submit');
    
    // Wait for login to complete
    await page.waitForLoadState('networkidle');
    
    // Try to access master dashboard
    await page.goto('https://upskill-staging.measurequick.com/master-dashboard/');
    await page.waitForLoadState('networkidle');
    
    // Should be redirected to regular dashboard with error
    const finalUrl = page.url();
    console.log('Final URL for regular trainer:', finalUrl);
    
    // Take screenshot
    await page.screenshot({ 
      path: `test-results/screenshots/master-dashboard-access-denied-${Date.now()}.png`,
      fullPage: true 
    });
    
    // Verify redirect
    expect(finalUrl).toContain('hvac-dashboard');
    expect(finalUrl).toContain('error=access_denied');
    console.log('✓ Regular trainer correctly denied access to Master Dashboard');
  });
});