process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

/**
 * Helper function for Elasticsearch API calls
 * @param url - The Elasticsearch endpoint path
 * @param method - HTTP method (GET, POST, PUT, DELETE)
 * @param body - Optional request body
 * @returns Promise with Elasticsearch response
 */
export default async function elasticHelper<T = any>(url: string, method: string = 'GET', body?: any): Promise<T> {
  const config = useRuntimeConfig()
  const baseUrl = config.api.elastic

  // Build request options
  const options: any = {
    method,
    headers: {
      'Content-Type': 'application/json',
      // Authorization: 'ApiKey ' + config.api.elastickey
    },
    // Only add body if it exists
    ...(body && { body })
  }

  // Enable these lines for debugging
  // console.log(`=== ELASTICSEARCH REQUEST === ${method} ${url}`, JSON.stringify(body, null, 2));

  try {
    const response = await $fetch<T>(`${baseUrl}/${url}`, options);

    // Enable this line for debugging
    // console.log(`=== ELASTICSEARCH RESPONSE === ${method} ${url}`, JSON.stringify(response, null, 2));

    return response;
  } catch (error) {
    console.error(`Elasticsearch error for ${method} ${url}:`, error);
    throw error;
  }
}