import type { IServiceContainer } from '@stock-bot/types';
import { IB_CONFIG } from '../shared/config';
import { fetchSession } from './fetch-session.action';

export async function fetchExchanges(services: IServiceContainer): Promise<unknown[] | null> {
  try {
    // First get session headers
    const sessionHeaders = await fetchSession(services);
    if (!sessionHeaders) {
      throw new Error('Failed to get session headers');
    }

    services.logger.info('🔍 Fetching exchanges with session headers...');

    // The URL for the exchange data API
    const exchangeUrl = IB_CONFIG.BASE_URL + IB_CONFIG.EXCHANGE_API;

    // Prepare headers - include all session headers plus any additional ones
    const requestHeaders = {
      ...sessionHeaders,
      Accept: 'application/json, text/plain, */*',
      'Accept-Language': 'en-US,en;q=0.9',
      'Cache-Control': 'no-cache',
      Pragma: 'no-cache',
      'Sec-Fetch-Dest': 'empty',
      'Sec-Fetch-Mode': 'cors',
      'Sec-Fetch-Site': 'same-origin',
      'X-Requested-With': 'XMLHttpRequest',
    };

    services.logger.info('📤 Making request to exchange API...', {
      url: exchangeUrl,
      headerCount: Object.keys(requestHeaders).length,
    });

    // Use fetch with proxy configuration
    const response = await fetch(exchangeUrl, {
      method: 'GET',
      headers: requestHeaders,
      proxy: IB_CONFIG.DEFAULT_PROXY,
    });

    if (!response.ok) {
      services.logger.error('❌ Exchange API request failed', {
        status: response.status,
        statusText: response.statusText,
      });
      return null;
    }

    const data = await response.json();
    const exchanges = data?.exchanges || [];
    services.logger.info('✅ Exchange data fetched successfully');

    if (services.mongodb) {
      services.logger.info('Saving IB exchanges to MongoDB...');
      await services.mongodb.batchUpsert('ibExchanges', exchanges, ['id', 'country_code']);
      services.logger.info('✅ Exchange IB data saved to MongoDB:', {
        count: exchanges.length,
      });
    } else {
      services.logger.warn('MongoDB service not available, skipping data persistence');
    }

    return exchanges;
  } catch (error) {
    services.logger.error('❌ Failed to fetch exchanges', { error });
    return null;
  }
}
