import { APIRequestContext, expect } from '@playwright/test';
import { execSync } from 'child_process';
import * as path from 'path';

/**
 * Fixture utilities for test setup and teardown
 */
export class FixtureUtils {
  /**
   * Check if real stack is running by calling health endpoint
   */
  static async isRealStackRunning(apiRequest: APIRequestContext, baseUrl: string): Promise<boolean> {
    try {
      const response = await apiRequest.get(`${baseUrl}/api/health`, {
        timeout: 5000,
      });
      return response.ok();
    } catch {
      return false;
    }
  }

  /**
   * Verify CORS preflight is working
   */
  static async verifyCORSPreflight(
    apiRequest: APIRequestContext,
    baseUrl: string,
    origin: string = 'http://localhost:3000',
  ): Promise<boolean> {
    try {
      const response = await apiRequest.fetch(`${baseUrl}/api/auth/login`, {
        method: 'OPTIONS',
        headers: {
          Origin: origin,
          'Access-Control-Request-Method': 'POST',
          'Access-Control-Request-Headers': 'Content-Type',
        },
      });

      if (!response.ok()) {
        return false;
      }

      const methods = response.headers()['access-control-allow-methods'] || '';
      return methods.includes('POST');
    } catch {
      return false;
    }
  }

  /**
   * Get API status
   */
  static async getApiStatus(apiRequest: APIRequestContext, baseUrl: string): Promise<any> {
    const response = await apiRequest.get(`${baseUrl}/api/status`);
    expect(response.ok()).toBeTruthy();
    return response.json();
  }

  /**
   * Clear user data (typically done via API reset endpoint if available)
   */
  static async clearUserData(apiRequest: APIRequestContext, baseUrl: string): Promise<void> {
    try {
      const response = await apiRequest.post(`${baseUrl}/api/test/reset`, {});
      expect(response.ok()).toBeTruthy();
    } catch {
      console.warn('Could not clear user data via API');
    }
  }

  /**
   * Seed database with test data (if endpoint available)
   */
  static async seedDatabase(apiRequest: APIRequestContext, baseUrl: string): Promise<void> {
    try {
      const response = await apiRequest.post(`${baseUrl}/api/test/seed`, {});
      expect(response.ok()).toBeTruthy();
    } catch {
      console.warn('Could not seed database via API');
    }
  }
}
