import type { CeoHandler } from '../ceo.handler';

export async function updateUniqueSymbols(
  this: CeoHandler,
  payload: any,
  _context: unknown
): Promise<unknown> {
  const action = payload?.action || 'get-posts'; // Default to get-posts if no action specified
  this.logger.info(`Starting update to get unique CEO symbols by ceoId for action: ${action}`);

  try {
    // Get unique ceoId values from the ceoSymbols collection
    const uniqueCeoIds = await this.mongodb.collection('ceoSymbols').distinct('ceoId');

    this.logger.info(`Found ${uniqueCeoIds.length} unique CEO IDs`);

    // Get detailed records for each unique ceoId (latest/first record)
    const uniqueSymbols = [];
    for (const ceoId of uniqueCeoIds) {
      const symbol = await this.mongodb
        .collection('ceoSymbols')
        .findOne({ ceoId }, { sort: { _id: -1 } }); // Get latest record

      if (symbol) {
        uniqueSymbols.push(symbol);
      }
    }

    this.logger.info(`Retrieved ${uniqueSymbols.length} unique symbol records`);

    // Schedule individual jobs for each unique symbol
    let scheduledJobs = 0;
    for (const symbol of uniqueSymbols) {
      // Schedule a job to process this individual symbol
      if (action === 'get-posts') {
        await this.scheduleOperation(
          'get-posts',
          {
            ceoId: symbol.ceoId,
            symbol: symbol.symbol,
            finished: symbol.finished || false,
          },
          { priority: 10 }
        );
      } else if (action === 'get-shorts') {
        await this.scheduleOperation(
          'get-shorts',
          {
            ceoId: symbol.ceoId,
            symbol: symbol.symbol,
            finished: symbol.finished || false,
          },
          { priority: 10 }
        );
      }

      scheduledJobs++;

      // Add small delay to avoid overwhelming the queue
      if (scheduledJobs % 10 === 0) {
        this.logger.debug(`Scheduled ${scheduledJobs} jobs so far`);
      }
    }

    this.logger.info(`Successfully scheduled ${scheduledJobs} individual symbol update jobs`);

    // Cache the results for monitoring
    await this.cacheSet(
      'unique-symbols-last-run',
      {
        timestamp: new Date().toISOString(),
        totalUniqueIds: uniqueCeoIds.length,
        totalRecords: uniqueSymbols.length,
        scheduledJobs,
      },
      1800
    ); // Cache for 30 minutes

    return {
      success: true,
      uniqueCeoIds: uniqueCeoIds.length,
      uniqueRecords: uniqueSymbols.length,
      scheduledJobs,
      timestamp: new Date().toISOString(),
    };
  } catch (error) {
    this.logger.error('Failed to update unique CEO symbols', { error });
    throw error;
  }
}
