import { getRandomUserAgent } from '@stock-bot/utils';
import type { CeoHandler } from '../ceo.handler';

export async function getShorts(this: CeoHandler, payload: any, _context: any): Promise<unknown> {
  const { ceoId, symbol, timestamp } = payload;
  const proxy = this.proxy?.getProxy();
  if (!proxy) {
    this.logger.warn('No proxy available for processing individual CEO symbol');
    return;
  }

  this.logger.debug(`Processing individual CEO symbol for ${symbol}`, {
    ceoId,
    timestamp,
  });
  try {
    // Update Shorts
    const response = await this.http.get(
      `https://api.ceo.ca/api/short_positions/one?symbol=${symbol}`,
      {
        proxy: proxy,
        headers: {
          'User-Agent': getRandomUserAgent(),
        },
      }
    );
    let shortCount = 0;

    if (response.ok) {
      const shortData = await response.json();
      if (shortData && shortData.positions) {
        shortCount = shortData.positions.length;
        await this.mongodb.batchUpsert('ceoShorts', shortData.positions, ['id']);
      }
    }

    this.logger.info(
      `Successfully processed CEO symbol ${symbol} shorts and found ${shortCount} positions`
    );

    return { ceoId, shortCount, timestamp };
  } catch (error) {
    this.logger.error(`Failed to process individual symbol ${symbol}`, {
      error,
      ceoId,
      timestamp,
    });
    throw error;
  }
}
