import { fetchExchanges } from './fetch-exchanges.action';
import { fetchSession } from './fetch-session.action';
import { fetchSymbols } from './fetch-symbols.action';

export async function fetchExchangesAndSymbols(services: IServiceContainer): Promise<unknown> {
  services.logger.info('Starting IB exchanges and symbols fetch job');

  try {
    // Fetch session headers first
    const sessionHeaders = await fetchSession(services);
    if (!sessionHeaders) {
      services.logger.error('Failed to get session headers for IB job');
      return { success: false, error: 'No session headers' };
    }

    services.logger.info('Session headers obtained, fetching exchanges...');

    // Fetch exchanges
    const exchanges = await fetchExchanges(services);
    services.logger.info('Fetched exchanges from IB', { count: exchanges?.length || 0 });

    // Fetch symbols
    services.logger.info('Fetching symbols...');
    const symbols = await fetchSymbols(services);
    services.logger.info('Fetched symbols from IB', { count: symbols?.length || 0 });

    return {
      success: true,
      exchangesCount: exchanges?.length || 0,
      symbolsCount: symbols?.length || 0,
    };
  } catch (error) {
    services.logger.error('Failed to fetch IB exchanges and symbols', { error });
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}
