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

/**
 * Debug test for Master Dashboard using authenticated session
 */

test.describe('Master Dashboard Debug', () => {
  
  test('Access Master Dashboard with authenticated session', async ({ authenticatedPage: page }) => {
    test.setTimeout(30000);
    const actions = new CommonActions(page);
    
    // We're already logged in as test_trainer
    console.log('Starting test - already authenticated as test_trainer');
    
    // First, navigate to regular dashboard to verify login worked
    await actions.navigateAndWait('/hvac-dashboard/');
    await actions.screenshot('regular-dashboard');
    
    // Try to navigate to master dashboard - should redirect since test_trainer doesn't have access
    await page.goto('https://upskill-staging.measurequick.com/master-dashboard/');
    await page.waitForLoadState('networkidle');
    await actions.screenshot('master-dashboard-attempt');
    
    // Check where we ended up
    const currentUrl = page.url();
    console.log('Current URL after master dashboard navigation:', currentUrl);
    
    // Expect to be redirected to regular dashboard with error
    if (currentUrl.includes('hvac-dashboard')) {
      console.log('Correctly redirected to regular dashboard (no access)');
      
      // Check for error parameter
      if (currentUrl.includes('error=access_denied')) {
        console.log('Access denied error parameter found - correct behavior');
      }
    } else if (currentUrl.includes('master-dashboard')) {
      console.log('ERROR: test_trainer should not have access to master dashboard!');
    } else if (currentUrl.includes('community-login')) {
      console.log('ERROR: Redirected to login page - authentication issue');
    }
  });
  
  test('Direct page content check', async ({ page }) => {
    test.setTimeout(30000);
    
    // Navigate directly to the master dashboard page (not logged in)
    await page.goto('https://upskill-staging.measurequick.com/master-dashboard/');
    await page.waitForLoadState('networkidle');
    
    // Check page source for shortcode
    const pageSource = await page.content();
    
    if (pageSource.includes('[hvac_master_dashboard]')) {
      console.log('Shortcode found in page source - not being processed');
    } else if (pageSource.includes('Master Dashboard')) {
      console.log('Master Dashboard text found in rendered content');
    } else if (pageSource.includes('Trainer Login')) {
      console.log('Redirected to login page (expected for non-authenticated user)');
    }
    
    // Check page title
    const title = await page.title();
    console.log('Page title:', title);
    
    // Take screenshot
    await page.screenshot({ 
      path: `test-results/screenshots/master-dashboard-source-${Date.now()}.png`,
      fullPage: true 
    });
  });
});