/**
 * Test utilities and helpers for AutoBackups Playwright tests
 */

class TestHelpers {
  /**
   * Wait for the Flask application to be ready
   * @param {import('@playwright/test').Page} page 
   */
  static async waitForAppReady(page) {
    await page.waitForLoadState('networkidle');
    
    // Wait for any loading indicators to disappear
    const loadingIndicators = page.locator('.loading, .spinner, [data-loading="true"]');
    if (await loadingIndicators.count() > 0) {
      await loadingIndicators.first().waitFor({ state: 'hidden', timeout: 10000 });
    }
  }

  /**
   * Take a full page screenshot with timestamp
   * @param {import('@playwright/test').Page} page 
   * @param {string} name 
   */
  static async takeTimestampedScreenshot(page, name) {
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    await page.screenshot({ 
      path: `test-results/${name}-${timestamp}.png`,
      fullPage: true 
    });
  }

  /**
   * Check if an element exists without throwing an error
   * @param {import('@playwright/test').Page} page 
   * @param {string} selector 
   */
  static async elementExists(page, selector) {
    try {
      const element = page.locator(selector);
      return (await element.count()) > 0;
    } catch {
      return false;
    }
  }

  /**
   * Wait for API response and validate
   * @param {import('@playwright/test').Page} page 
   * @param {string} url 
   * @param {number} expectedStatus 
   */
  static async waitForApiResponse(page, url, expectedStatus = 200) {
    const response = await page.waitForResponse(url);
    return response.status() === expectedStatus;
  }

  /**
   * Fill form if fields exist
   * @param {import('@playwright/test').Page} page 
   * @param {Object} formData 
   */
  static async fillFormIfExists(page, formData) {
    for (const [fieldName, value] of Object.entries(formData)) {
      const field = page.locator(`input[name="${fieldName}"], select[name="${fieldName}"], textarea[name="${fieldName}"]`);
      if (await field.count() > 0) {
        if (await field.getAttribute('type') === 'checkbox') {
          if (value) await field.check();
        } else {
          await field.fill(String(value));
        }
      }
    }
  }

  /**
   * Get all console logs from the page
   * @param {import('@playwright/test').Page} page 
   */
  static setupConsoleLogging(page) {
    page.on('console', msg => {
      console.log(`Browser console [${msg.type()}]: ${msg.text()}`);
    });

    page.on('pageerror', error => {
      console.error(`Browser error: ${error.message}`);
    });
  }

  /**
   * Common test data for forms
   */
  static getTestData() {
    return {
      sampleConfig: {
        backup_destination: 'C:\\TestBackups',
        observation_directories: ['C:\\TestProjects'],
        schedule: 'daily',
        max_backup_age_days: 30
      },
      sampleProject: {
        name: 'Test Project',
        path: 'C:\\TestProjects\\TestProject.s7p',
        schedule: 'manual'
      }
    };
  }
}

module.exports = { TestHelpers };
