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

/**
 * Test to deploy the HVAC plugin via web installer
 */
test.describe('Plugin Installation Test', () => {
  test('Deploy HVAC plugin via web installer', async ({ page }) => {
    console.log('Starting HVAC plugin installation via web installer');
    
    // Step 1: First, let's try to upload the installer via a test endpoint
    console.log('Step 1: Attempting to run the installer');
    
    // Try to access the installer directly (this assumes we can place it on the server)
    const installerUrl = `${STAGING_URL}/plugin-backups/complete-hvac-installer.php?install_key=hvac-staging-deploy-2025`;
    
    try {
      console.log(`Accessing installer at: ${installerUrl}`);
      await page.goto(installerUrl, { timeout: 120000 }); // 2 minute timeout
      await page.waitForLoadState('networkidle');
      
      // Take screenshot of the installation result
      await page.screenshot({ path: 'test-results/installer/installation-result.png' });
      
      // Get the installation output
      const pageContent = await page.textContent('body');
      console.log('Installation output preview:');
      console.log(pageContent?.substring(0, 1000) + '...');
      
      // Check for success indicators
      const hasSuccess = pageContent?.includes('Installation Complete!');
      const hasError = pageContent?.includes('ERROR:') || pageContent?.includes('Failed');
      
      console.log(`Installation successful: ${hasSuccess}`);
      console.log(`Installation errors detected: ${hasError}`);
      
      // If installation worked, verify we can now access admin
      if (hasSuccess) {
        console.log('Step 2: Testing admin access with new credentials');
        
        await page.goto(`${STAGING_URL}/wp-admin/`);
        await page.waitForLoadState('networkidle');
        
        // Try to login with test_admin
        const hasLoginForm = await page.locator('input[name="log"]').count() > 0;
        if (hasLoginForm) {
          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');
          
          const currentUrl = page.url();
          const loginSuccess = !currentUrl.includes('wp-login.php');
          console.log(`Admin login successful: ${loginSuccess}`);
          
          if (loginSuccess) {
            console.log('Step 3: Checking for HVAC plugin in admin');
            
            // Check if we can see HVAC menu items
            const hvacMenuItems = await page.locator('text="HVAC"').count();
            const zohoMenuItems = await page.locator('text="Zoho"').count();
            
            console.log(`HVAC menu items found: ${hvacMenuItems}`);
            console.log(`Zoho menu items found: ${zohoMenuItems}`);
            
            // Take screenshot of wp-admin dashboard
            await page.screenshot({ path: 'test-results/installer/wp-admin-dashboard.png' });
            
            // Try to access the Zoho settings page
            if (hvacMenuItems > 0 || zohoMenuItems > 0) {
              console.log('Step 4: Testing Zoho CRM settings access');
              
              // Look for Zoho CRM settings in the menu
              const zohoSettingsLink = page.locator('a:has-text("Zoho"), a[href*="zoho"]').first();
              const hasZohoLink = await zohoSettingsLink.count() > 0;
              
              if (hasZohoLink) {
                await zohoSettingsLink.click();
                await page.waitForLoadState('networkidle');
                await page.screenshot({ path: 'test-results/installer/zoho-settings-page.png' });
                
                const zohoPageContent = await page.textContent('body');
                const hasConnectionTest = zohoPageContent?.includes('Test Connection');
                console.log(`Zoho settings page accessible: ${hasConnectionTest}`);
              }
            }
          }
        }
      }
      
    } catch (error) {
      console.log(`Installer error: ${error}`);
      
      // Let's try an alternative approach - check if we can upload files
      console.log('Step Alternative: Checking upload capabilities');
      
      // Try to check if there's a file upload capability
      await page.goto(`${STAGING_URL}/wp-admin/plugin-install.php`);
      await page.waitForLoadState('networkidle');
      
      const currentUrl = page.url();
      if (!currentUrl.includes('wp-login.php')) {
        console.log('Can access plugin install page without login - this is unexpected');
      } else {
        console.log('Redirected to login as expected');
      }
    }
    
    console.log('Plugin installation test completed');
  });
  
  test('Verify basic site functionality after installation', async ({ page }) => {
    console.log('Step 1: Verifying basic site functionality');
    
    // Check if the site still loads
    await page.goto(STAGING_URL);
    await page.waitForLoadState('networkidle');
    
    const title = await page.title();
    console.log(`Site title: ${title}`);
    
    // Check for any PHP errors on homepage
    const pageContent = await page.textContent('body');
    const hasPhpError = pageContent?.includes('Fatal error') || pageContent?.includes('Parse error');
    console.log(`PHP errors detected: ${hasPhpError}`);
    
    // Check if WordPress is still functioning
    const hasWpContent = pageContent?.includes('wp-') || pageContent?.includes('WordPress');
    console.log(`WordPress content detected: ${hasWpContent}`);
    
    await page.screenshot({ path: 'test-results/installer/post-install-homepage.png' });
    
    console.log('Basic functionality verification completed');
  });
});