import { callExplorerApi } from '../../core/explorerApi';
import { SearchResult } from '../../types/search';
import { logger } from '../../utils/logger';

/**
 * Search for blocks, transactions, addresses, or tokens
 * 
 * @param {string} query - The search query (block number, transaction hash, address, etc.)
 * @returns {Promise<SearchResult | null>} - Basic search result with type and ID, or null if not found
 */
export async function search(query: string): Promise<SearchResult | null> {
  try {
    logger.debug(`Searching for: ${query}`);
    

    const response = await callExplorerApi<any>('search', { q: query });
    
    if (response.status !== 'success' || !response.type) {
      return null;
    }
    
    let id: string;
    
    switch(response.type) {
      case 'block':
        id = response.data?.number || response.data?.hash;
        break;
      case 'transaction':
        id = response.data?.hash;
        break;
      case 'address':
      case 'token':
        id = response.data?.address;
        break;
      default:
        id = query;
    }
    
    return {
      type: response.type,
      id: id
    };
  } catch (error) {
    logger.error('Error in search:', error);
    return null;
  }
}