import { test, expect } from '@playwright/test';
import { STAGING_URL, PATHS } from './config/staging-config';

/**
 * Test to verify the Zoho CRM integration with the new domain
 * This test verifies:
 * 1. The login functionality works
 * 2. The dashboard loads correctly
 * 3. The Zoho CRM integration shows the correct domain in OAuth Redirect URI
 */
test.describe('Zoho Domain Update Verification', () => {
  test('Login and verify dashboard', async ({ page }) => {
    console.log('Step 1: Logging in as test_trainer');
    
    // Navigate to WordPress login page
    await page.goto(`${STAGING_URL}/wp-login.php`);
    
    // Verify the login page loaded
    const loginTitle = await page.title();
    console.log(`Login page title: ${loginTitle}`);
    
    // Fill in login credentials
    await page.fill('#user_login', 'test_trainer');
    await page.fill('#user_pass', 'Test123!');
    
    // Take screenshot before login
    await page.screenshot({ path: 'test-results/zoho-verification/before-login.png' });
    
    // Click login button
    await page.click('#wp-submit');
    
    // Wait for navigation
    await page.waitForLoadState('networkidle');
    
    // Take screenshot after login
    await page.screenshot({ path: 'test-results/zoho-verification/after-login.png' });
    
    // URL might not change on failed login, so check if we're still on the login page
    const currentUrl = page.url();
    console.log(`Current URL after login: ${currentUrl}`);
    
    if (currentUrl.includes('wp-login.php')) {
      // Check if there's an error message
      const errorMessage = await page.textContent('.login-error, .login_error');
      if (errorMessage) {
        console.log(`Login error: ${errorMessage}`);
      }
      console.log('Login might have failed, trying to navigate to admin directly');
    }
    
    // Navigate to the WordPress admin directly
    console.log('Step 2: Navigating to WordPress admin');
    await page.goto(`${STAGING_URL}/wp-admin/`);
    await page.waitForLoadState('networkidle');
    
    // Verify admin access
    const adminTitle = await page.title();
    console.log(`Admin page title: ${adminTitle}`);
    console.log(`Admin page should contain "Dashboard": ${adminTitle.includes('Dashboard')}`);
    
    // Check if admin panel loaded
    const adminPanel = page.locator('#wpcontent');
    const adminPanelExists = await adminPanel.isVisible();
    console.log(`Admin panel is visible: ${adminPanelExists}`);
    
    // Take screenshot of admin panel
    await page.screenshot({ path: 'test-results/zoho-verification/admin-panel.png' });
    
    // Try to find any HVAC Community Events menu (may be in different formats)
    console.log('Looking for HVAC Community Events menu...');
    const menuLocators = [
      'li#toplevel_page_hvac-community-events',
      'li.menu-top:has-text("HVAC Community Events")',
      '#adminmenu li:has-text("HVAC")',
      '#adminmenu li:has-text("Community Events")'
    ];
    
    let hvacMenu = null;
    let menuExists = false;
    
    for (const locator of menuLocators) {
      const menu = page.locator(locator);
      if (await menu.count() > 0 && await menu.isVisible()) {
        hvacMenu = menu;
        menuExists = true;
        console.log(`Found HVAC menu using locator: ${locator}`);
        break;
      }
    }
    
    console.log(`HVAC Community Events menu exists: ${menuExists}`);
    
    // If menu exists, try to access Zoho CRM section
    if (menuExists && hvacMenu) {
      await hvacMenu.click();
      await page.waitForTimeout(1000); // Small delay for submenu to appear
      
      // Take screenshot of admin menu
      await page.screenshot({ path: 'test-results/zoho-verification/admin-menu.png' });
      
      // Look for the Zoho CRM Sync submenu item using multiple potential selectors
      const zohoCrmMenuItems = [
        'a:has-text("Zoho CRM Sync")',
        'li:has-text("Zoho CRM")',
        'a[href*="zoho"]'
      ];
      
      let zohoCrmMenuItem = null;
      for (const selector of zohoCrmMenuItems) {
        const menuItem = page.locator(selector);
        if (await menuItem.count() > 0 && await menuItem.isVisible()) {
          zohoCrmMenuItem = menuItem;
          console.log(`Found Zoho CRM menu item using selector: ${selector}`);
          break;
        }
      }
      
      if (zohoCrmMenuItem) {
        console.log('Step 3: Navigating to Zoho CRM Sync page');
        await zohoCrmMenuItem.click();
        await page.waitForLoadState('networkidle');
        
        // Take screenshot of Zoho CRM page
        await page.screenshot({ path: 'test-results/zoho-verification/zoho-crm-page.png' });
        
        // Verify the page title
        const zohoCrmTitle = await page.title();
        console.log(`Zoho CRM page title: ${zohoCrmTitle}`);
        expect(zohoCrmTitle).toContain('Zoho CRM Sync');
        
        // Verify staging mode banner is present
        const stagingBanner = page.locator('.notice-info:has-text("STAGING MODE ACTIVE")');
        const bannerVisible = await stagingBanner.isVisible();
        console.log(`Staging mode banner visible: ${bannerVisible}`);
        expect(bannerVisible).toBeTruthy();
        
        // Check for the OAuth Redirect URI in the banner
        const redirectUriText = await page.textContent('.notice-info');
        console.log(`Banner text: ${redirectUriText}`);
        
        // Verify the banner contains the new domain
        expect(redirectUriText).toContain('upskill-staging.measurequick.com');
        expect(redirectUriText).not.toContain('wordpress-974670-5399585.cloudwaysapps.com');
        
        // Test the connection button to verify enhanced error reporting
        console.log('Step 4: Testing Zoho CRM connection');
        const testButton = page.locator('button#test-connection');
        if (await testButton.isVisible()) {
          await testButton.click();
          await page.waitForTimeout(3000); // Wait for the response
          
          // Take screenshot of connection test result
          await page.screenshot({ path: 'test-results/zoho-verification/connection-test-result.png' });
          
          // Check for error message with enhanced details
          const errorMessage = page.locator('#connection-status');
          const errorVisible = await errorMessage.isVisible();
          console.log(`Error message visible: ${errorVisible}`);
          
          if (errorVisible) {
            const errorText = await errorMessage.textContent();
            console.log(`Error message: ${errorText}`);
            
            // Verify the error message contains detailed information
            expect(errorText).toContain('Connection failed');
            
            // Look for debug information section (enhanced reporting)
            const debugToggle = page.locator('button.toggle-debug');
            const debugToggleVisible = await debugToggle.isVisible();
            
            if (debugToggleVisible) {
              console.log('Debug information toggle found, clicking to expand...');
              await debugToggle.click();
              await page.waitForTimeout(1000);
              
              // Take screenshot with expanded debug info
              await page.screenshot({ path: 'test-results/zoho-verification/error-debug-expanded.png' });
              
              // Verify debug information is shown
              const debugInfo = page.locator('.hvac-zoho-debug');
              const debugVisible = await debugInfo.isVisible();
              expect(debugVisible).toBeTruthy();
              
              // Look for the new domain in debug information
              const debugText = await debugInfo.textContent();
              expect(debugText).toContain('upskill-staging.measurequick.com');
            }
          }
        }
      } else {
        console.log('Zoho CRM Sync menu item not found');
      }
    } else {
      console.log('HVAC Community Events menu not found');
      // Take a screenshot of the whole admin panel to debug
      await page.screenshot({ path: 'test-results/zoho-verification/admin-panel-no-menu.png', fullPage: true });
    }
  });
});