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

/**
 * Test Zoho admin interface with enhanced error reporting
 */
test.describe('Zoho Admin Interface Test', () => {
  test('Login as admin and test Zoho connection', async ({ page }) => {
    console.log('Testing Zoho admin interface with test_admin credentials');
    
    // Step 1: Login to WordPress admin
    console.log('Step 1: Logging into WordPress admin');
    await page.goto(`${STAGING_URL}/wp-admin/`);
    await page.waitForLoadState('networkidle');
    
    // Should be redirected to login page
    expect(page.url()).toContain('wp-login.php');
    
    // Login with test_admin credentials
    await page.fill('input[name="log"]', 'test_admin');
    await page.fill('input[name="pwd"]', 'hvac_staging_2025');
    await page.click('input[type="submit"]');
    await page.waitForLoadState('networkidle');
    
    console.log('Current URL after login:', page.url());
    
    // Verify we're in wp-admin
    const isInAdmin = page.url().includes('/wp-admin/') && !page.url().includes('wp-login.php');
    console.log(`Successfully logged into admin: ${isInAdmin}`);
    
    if (!isInAdmin) {
      console.log('Login failed - taking screenshot');
      await page.screenshot({ path: 'test-results/zoho/login-failed.png' });
      return;
    }
    
    // Take screenshot of admin dashboard
    await page.screenshot({ path: 'test-results/zoho/admin-dashboard.png' });
    
    // Step 2: Look for HVAC menu items
    console.log('Step 2: Looking for HVAC menu items');
    
    const hvacMenuItems = await page.locator('#adminmenu a:has-text("HVAC")').count();
    const zohoMenuItems = await page.locator('#adminmenu a:has-text("Zoho")').count();
    
    console.log(`HVAC menu items found: ${hvacMenuItems}`);
    console.log(`Zoho menu items found: ${zohoMenuItems}`);
    
    // Try to find Zoho CRM settings
    const possibleZohoSelectors = [
      '#adminmenu a:has-text("Zoho")',
      '#adminmenu a[href*="zoho"]',
      '#adminmenu a:has-text("CRM")',
      '#adminmenu a:has-text("HVAC")',
      'a:has-text("Zoho CRM")'
    ];
    
    let zohoLinkFound = false;
    for (const selector of possibleZohoSelectors) {
      const count = await page.locator(selector).count();
      if (count > 0) {
        console.log(`Found potential Zoho link with selector: ${selector}`);
        zohoLinkFound = true;
        
        // Try to click it
        await page.locator(selector).first().click();
        await page.waitForLoadState('networkidle');
        await page.screenshot({ path: 'test-results/zoho/zoho-page.png' });
        
        console.log('Clicked Zoho menu, current URL:', page.url());
        break;
      }
    }
    
    if (!zohoLinkFound) {
      console.log('No Zoho menu found, checking all menu items');
      const allMenuItems = await page.$$eval('#adminmenu a', links => 
        links.map(link => ({ text: link.textContent?.trim(), href: link.href }))
      );
      
      console.log('All admin menu items:');
      for (const item of allMenuItems.slice(0, 20)) {
        console.log(`  - ${item.text}: ${item.href}`);
      }
    }
    
    // Step 3: Look for Zoho settings in any admin pages
    console.log('Step 3: Searching for Zoho settings in admin pages');
    
    // Try direct URLs that might contain Zoho settings
    const possibleZohoUrls = [
      '/wp-admin/admin.php?page=zoho-crm',
      '/wp-admin/admin.php?page=zoho-settings',
      '/wp-admin/admin.php?page=hvac-zoho',
      '/wp-admin/admin.php?page=hvac-settings',
      '/wp-admin/options-general.php'
    ];
    
    for (const urlPath of possibleZohoUrls) {
      try {
        console.log(`Trying URL: ${urlPath}`);
        await page.goto(`${STAGING_URL}${urlPath}`);
        await page.waitForLoadState('networkidle');
        
        const pageContent = await page.textContent('body');
        const hasZohoContent = pageContent?.includes('Zoho') || pageContent?.includes('zoho') || 
                              pageContent?.includes('CRM') || pageContent?.includes('Test Connection');
        
        console.log(`${urlPath} contains Zoho content: ${hasZohoContent}`);
        
        if (hasZohoContent) {
          await page.screenshot({ path: `test-results/zoho/zoho-settings-${urlPath.replace(/[\/\?=]/g, '-')}.png` });
          
          // Look for Test Connection button
          const testButton = page.locator('button:has-text("Test Connection"), input[value*="Test Connection"]');
          const testButtonCount = await testButton.count();
          
          if (testButtonCount > 0) {
            console.log('Found Test Connection button - clicking it');
            await testButton.click();
            await page.waitForTimeout(3000); // Wait for AJAX response
            
            await page.screenshot({ path: 'test-results/zoho/test-connection-result.png' });
            
            // Check for error messages or success messages
            const pageContentAfter = await page.textContent('body');
            const hasErrorInfo = pageContentAfter?.includes('no_token') || 
                                pageContentAfter?.includes('Connection failed') ||
                                pageContentAfter?.includes('Error Code') ||
                                pageContentAfter?.includes('Debug Information');
            
            console.log(`Enhanced error reporting visible: ${hasErrorInfo}`);
            
            if (hasErrorInfo) {
              console.log('✓ Enhanced error reporting is working!');
              console.log('Error details found on page');
            }
          }
          break;
        }
      } catch (error) {
        console.log(`Error accessing ${urlPath}: ${error}`);
      }
    }
    
    console.log('Zoho admin interface test completed');
  });
});