import type { BaseHandler } from '@stock-bot/handlers';
import type { DataIngestionServices } from '../../../types';
import { EOD_CONFIG } from '../shared';

export async function fetchExchanges(
  this: BaseHandler<DataIngestionServices>
): Promise<{ success: boolean; count: number }> {;
  const logger = this.logger;

  try {
    logger.info('Fetching EOD exchanges list');

    // Get API key from config
    const apiKey = EOD_CONFIG.API_TOKEN;
    if (!apiKey) {
      throw new Error('EOD API key not configured');
    }
    
    // Build URL with query parameters
    const url = new URL('https://eodhd.com/api/exchanges-list/');
    url.searchParams.append('api_token', apiKey);
    url.searchParams.append('fmt', 'json');

    // Fetch exchanges from EOD API using Bun fetch
    const response = await fetch(url.toString());
    
    if (!response.ok) {
      throw new Error(`EOD Exchanges API returned ${response.status}: ${response.statusText}`);
    }

    const exchanges = await response.json();

    if (!Array.isArray(exchanges)) {
      throw new Error('Invalid response format from EOD API - expected array');
    }
    logger.info(`Fetched ${exchanges.length} exchanges from EOD`);
    
    // Log some example exchanges
    if (exchanges.length > 0) {
      logger.debug('Sample exchanges:', {
        count: exchanges.length,
        samples: exchanges.slice(0, 5).map(e => ({ 
          code: e.Code, 
          name: e.Name, 
          country: e.Country 
        }))
      });
    }

    const result = await this.mongodb.batchUpsert('eodExchanges', exchanges, ['Code']);
    
    logger.info(`Successfully saved exchanges to MongoDB`, {
      total: exchanges.length,
      inserted: result.insertedCount,
      updated: exchanges.length - result.insertedCount
    });

    return {
      success: true,
      count: result.insertedCount
    };
  } catch (error) {
    logger.error('Failed to fetch or save EOD exchanges', { error });
    throw error;
  }
}


