import { getAccessToken } from '../auth';
import { API_ENDPOINTS, DEFAULT_HEADERS, ERROR_MESSAGES } from './constants';

/**
 * Helper function to make authenticated API calls to CrowdStrike API
 * @param auth Authentication parameters
 * @param endpoint API endpoint to call
 * @param method HTTP method
 * @param body Request body (optional)
 * @param params URL parameters (optional)
 * @returns API response
 */
export async function makeAuthenticatedApiCall(
  auth: {
    base_url: string;
    client_id: string;
    client_secret: string;
  },
  endpoint: string,
  method: 'GET' | 'POST' | 'PUT' | 'DELETE',
  body?: any,
  params?: Record<string, string>
) {
  try {
    // Get access token
    const tokenResponse = await getAccessToken(auth);
    
    // Prepare URL with query parameters if provided
    let url = `${auth.base_url}${endpoint}`;
    if (params) {
      const queryParams = new URLSearchParams();
      Object.entries(params).forEach(([key, value]) => {
        queryParams.append(key, value);
      });
      url = `${url}?${queryParams.toString()}`;
    }
    
    // Prepare request options
    const options: RequestInit = {
      method,
      headers: {
        ...DEFAULT_HEADERS,
        'Authorization': `Bearer ${tokenResponse.access_token}`,
      },
    };
    
    // Add body if provided
    if (body) {
      options.body = JSON.stringify(body);
    }
    
    // Make API call
    const response = await fetch(url, options);
    
    // Handle response
    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`API call failed: ${response.status} ${errorText}`);
    }
    
    return await response.json();
  } catch (error) {
    if (error instanceof Error) {
      // Enhance error with more context
      throw new Error(`${error.message} (Endpoint: ${endpoint})`);
    }
    throw error;
  }
}

/**
 * Format error response for Active Pieces
 * @param error Error object
 * @returns Formatted error response
 */
export function formatErrorResponse(error: unknown) {
  if (error instanceof Error) {
    return {
      success: false,
      error: error.message,
    };
  }
  return {
    success: false,
    error: ERROR_MESSAGES.INVALID_RESPONSE,
  };
}

/**
 * Validate required parameters
 * @param params Parameters to validate
 * @param requiredParams List of required parameter names
 * @throws Error if any required parameter is missing
 */
export function validateRequiredParams(
  params: Record<string, any>,
  requiredParams: string[]
) {
  const missingParams = requiredParams.filter(param => !params[param]);
  if (missingParams.length > 0) {
    throw new Error(`Missing required parameters: ${missingParams.join(', ')}`);
  }
}
