import fetch from 'node-fetch';
import { getExplorerApiUrl } from '../config';
import { logger } from '../utils/logger';

/**
 * Make an API call to the Explorer DB API
 * @template T - The expected return type
 * @param {string} endpoint - The API endpoint (without leading slash)
 * @param {Record<string, any>} queryParams - Query parameters for the request
 * @returns {Promise<T>} - A promise that resolves with the result from the API
 */
export async function callExplorerApi<T = unknown>(
  endpoint: string, 
  queryParams: Record<string, any> = {}
): Promise<T> {
  try {
    const apiUrl = getExplorerApiUrl();
    const queryString = Object.entries(queryParams)
      .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
      .join('&');
    
    const url = `${apiUrl}/${endpoint}${queryString ? `?${queryString}` : ''}`;
    
    logger.debug(`Making request to: ${url}`);
    
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error(`Explorer API responded with status: ${response.status}`);
    }
    
    const data = await response.json();
    logger.debug('API Response Structure:', JSON.stringify(data, null, 2).substring(0, 200) + '...');
    if (data.status === 'error') {
      throw new Error(data.message || 'Explorer API call failed');
    }
    if (data.status === 'success') {
      return data as T;
    }
    if (data.data !== undefined) {
      return data as T;
    }
    

    return data as T;
  } catch (error) {
    logger.error('Error calling Explorer API:', error);
    throw error;
  }
} 