import { Browser } from '@stock-bot/browser';
import type { IServiceContainer } from '@stock-bot/handlers';
import { IB_CONFIG } from '../shared/config';

export async function fetchSession(
  services: IServiceContainer
): Promise<Record<string, string> | undefined> {
  try {
    await Browser.initialize({
      headless: true,
      timeout: IB_CONFIG.BROWSER_TIMEOUT,
      blockResources: false,
    });
    services.logger.info('✅ Browser initialized');

    const { page } = await Browser.createPageWithProxy(
      IB_CONFIG.BASE_URL + IB_CONFIG.PRODUCTS_PAGE,
      IB_CONFIG.DEFAULT_PROXY
    );
    services.logger.info('✅ Page created with proxy');

    const headersPromise = new Promise<Record<string, string> | undefined>(resolve => {
      let resolved = false;

      page.onNetworkEvent(event => {
        if (event.url.includes('/webrest/search/product-types/summary')) {
          if (event.type === 'request') {
            try {
              resolve(event.headers);
            } catch (e) {
              resolve(undefined);
              services.logger.debug('Raw Summary Response error', { error: (e as Error).message });
            }
          }
        }
      });

      // Timeout fallback
      setTimeout(() => {
        if (!resolved) {
          resolved = true;
          services.logger.warn('Timeout waiting for headers');
          resolve(undefined);
        }
      }, IB_CONFIG.HEADERS_TIMEOUT);
    });

    services.logger.info('⏳ Waiting for page load...');
    await page.waitForLoadState('domcontentloaded', { timeout: IB_CONFIG.PAGE_LOAD_TIMEOUT });
    services.logger.info('✅ Page loaded');

    //Products tabs
    services.logger.info('🔍 Looking for Products tab...');
    const productsTab = page.locator('#productSearchTab[role="tab"][href="#products"]');
    await productsTab.waitFor({ timeout: IB_CONFIG.ELEMENT_TIMEOUT });
    services.logger.info('✅ Found Products tab');
    services.logger.info('🖱️ Clicking Products tab...');
    await productsTab.click();
    services.logger.info('✅ Products tab clicked');

    // New Products Checkbox
    services.logger.info('🔍 Looking for "New Products Only" radio button...');
    const radioButton = page.locator('span.checkbox-text:has-text("New Products Only")');
    await radioButton.waitFor({ timeout: IB_CONFIG.ELEMENT_TIMEOUT });
    services.logger.info(`🎯 Found "New Products Only" radio button`);
    await radioButton.first().click();
    services.logger.info('✅ "New Products Only" radio button clicked');

    // Wait for and return headers immediately when captured
    services.logger.info('⏳ Waiting for headers to be captured...');
    const headers = await headersPromise;
    page.close();
    if (headers) {
      services.logger.info('✅ Headers captured successfully');
    } else {
      services.logger.warn('⚠️ No headers were captured');
    }

    return headers;
  } catch (error) {
    services.logger.error('Failed to fetch IB symbol summary', { error });
    return;
  }
}
