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

/**
 * Test to verify the HVAC plugin has been successfully deployed with domain fixes
 */
test.describe('Verify Plugin Deployment', () => {
  test('Check if HVAC plugin files are accessible after deployment', async ({ page }) => {
    console.log('Step 1: Checking plugin file accessibility after deployment');
    
    // Test plugin file access again
    const pluginUrls = [
      `${STAGING_URL}/wp-content/plugins/hvac-community-events/hvac-community-events.php`,
      `${STAGING_URL}/wp-content/plugins/hvac-community-events/assets/css/hvac-dashboard.css`,
      `${STAGING_URL}/wp-content/plugins/hvac-community-events/assets/js/hvac-dashboard.js`,
      `${STAGING_URL}/wp-content/plugins/hvac-community-events/includes/zoho/zoho-config.php`
    ];
    
    for (const url of pluginUrls) {
      try {
        const response = await page.request.get(url);
        console.log(`${url}: ${response.status()} ${response.statusText()}`);
        
        if (response.status() === 200) {
          const content = await response.text();
          console.log(`  Content length: ${content.length} characters`);
          
          // Check for specific fixes in zoho-config.php
          if (url.includes('zoho-config.php')) {
            const hasDynamicDomain = content.includes('get_site_url()') || content.includes('upskill-staging.measurequick.com');
            console.log(`  Contains domain fix: ${hasDynamicDomain}`);
          }
        }
      } catch (error) {
        console.log(`${url}: Error - ${error}`);
      }
    }
  });
  
  test('Check for HVAC plugin indicators on homepage', async ({ page }) => {
    console.log('Step 2: Checking for HVAC plugin indicators after deployment');
    
    await page.goto(STAGING_URL);
    await page.waitForLoadState('networkidle');
    
    // Check HTML source for plugin indicators
    const htmlContent = await page.content();
    
    // Plugin-specific indicators
    const indicators = [
      'hvac-community-events',
      'hvac-dashboard',
      'hvac-registration',
      'trainer-profile',
      'community-login'
    ];
    
    let foundIndicators = 0;
    for (const indicator of indicators) {
      if (htmlContent.includes(indicator)) {
        console.log(`✓ Found indicator: ${indicator}`);
        foundIndicators++;
      }
    }
    
    console.log(`Total HVAC indicators found: ${foundIndicators}`);
    
    // Check for plugin assets loading
    const cssLinks = await page.$$eval('link[rel="stylesheet"]', links => 
      links.map(link => link.href).filter(href => href.includes('hvac'))
    );
    
    const jsScripts = await page.$$eval('script[src]', scripts => 
      scripts.map(script => script.src).filter(src => src.includes('hvac'))
    );
    
    console.log(`HVAC CSS files loading: ${cssLinks.length}`);
    console.log(`HVAC JS files loading: ${jsScripts.length}`);
    
    if (cssLinks.length > 0) console.log('HVAC CSS files:', cssLinks);
    if (jsScripts.length > 0) console.log('HVAC JS files:', jsScripts);
    
    // Take screenshot for comparison
    await page.screenshot({ path: 'test-results/deployment/post-deployment-homepage.png' });
  });
  
  test('Test WordPress REST API endpoints from HVAC plugin', async ({ page }) => {
    console.log('Step 3: Testing HVAC plugin REST API endpoints');
    
    // Test some potential API endpoints
    const apiEndpoints = [
      `${STAGING_URL}/wp-json/`,
      `${STAGING_URL}/wp-json/wp/v2/`,
      `${STAGING_URL}/wp-json/tribe/events/v1/`,
      `${STAGING_URL}/wp-json/hvac/v1/`
    ];
    
    for (const endpoint of apiEndpoints) {
      try {
        const response = await page.request.get(endpoint);
        console.log(`${endpoint}: ${response.status()} ${response.statusText()}`);
        
        if (response.status() === 200) {
          const content = await response.text();
          const hasHvacRoutes = content.includes('hvac') || content.includes('zoho');
          console.log(`  Contains HVAC routes: ${hasHvacRoutes}`);
        }
      } catch (error) {
        console.log(`${endpoint}: Error - ${error}`);
      }
    }
  });
  
  test('Check WordPress admin redirect behavior', async ({ page }) => {
    console.log('Step 4: Testing WordPress admin access');
    
    await page.goto(`${STAGING_URL}/wp-admin/`);
    await page.waitForLoadState('networkidle');
    
    const currentUrl = page.url();
    const isLoginPage = currentUrl.includes('wp-login.php');
    console.log(`Redirected to login: ${isLoginPage}`);
    console.log(`Current URL: ${currentUrl}`);
    
    if (isLoginPage) {
      // Check if we have the login form
      const hasLoginForm = await page.locator('input[name="log"]').count() > 0;
      console.log(`Login form present: ${hasLoginForm}`);
      
      // Take screenshot of login page
      await page.screenshot({ path: 'test-results/deployment/wp-login-page.png' });
    }
  });
});