import {
  BaseHandler,
  Handler,
  Operation,
  ScheduledOperation,
  type IServiceContainer,
} from '@stock-bot/handlers';
import { syncQMSymbols } from './operations/qm-symbols.operations';
import { getSyncStatus } from './operations/sync-status.operations';
import { syncSymbolsFromProvider } from './operations/sync-symbols-from-provider.operations';

@Handler('symbols')
class SymbolsHandler extends BaseHandler {
  constructor(services: IServiceContainer) {
    super(services);
  }

  /**
   * Sync symbols from QuestionsAndMethods API
   */
  @ScheduledOperation('sync-qm-symbols', '0 2 * * *', {
    priority: 5,
    description: 'Daily sync of QM symbols at 2 AM',
  })
  async syncQMSymbols(): Promise<{ processed: number; created: number; updated: number }> {
    this.log('info', 'Starting QM symbols sync...');
    return syncQMSymbols({}, this.services);
  }

  /**
   * Sync symbols from specific provider
   */
  @Operation('sync-symbols-qm')
  @ScheduledOperation('sync-symbols-qm', '0 4 * * *', {
    priority: 5,
    description: 'Daily sync of symbols from QM provider at 4 AM',
  })
  async syncSymbolsQM(): Promise<unknown> {
    return this.syncSymbolsFromProvider({ provider: 'qm', clearFirst: false });
  }

  @Operation('sync-symbols-eod')
  async syncSymbolsEOD(payload: { provider: string; clearFirst?: boolean }): Promise<unknown> {
    return this.syncSymbolsFromProvider({ ...payload, provider: 'eod' });
  }

  @Operation('sync-symbols-ib')
  async syncSymbolsIB(payload: { provider: string; clearFirst?: boolean }): Promise<unknown> {
    return this.syncSymbolsFromProvider({ ...payload, provider: 'ib' });
  }

  /**
   * Get sync status for symbols
   */
  @Operation('sync-status')
  async getSyncStatus(): Promise<unknown> {
    this.log('info', 'Getting symbol sync status...');
    return getSyncStatus({}, this.services);
  }

  /**
   * Internal method to sync symbols from a provider
   */
  private async syncSymbolsFromProvider(payload: {
    provider: string;
    clearFirst?: boolean;
  }): Promise<unknown> {
    this.log('info', 'Syncing symbols from provider', { provider: payload.provider });
    return syncSymbolsFromProvider(payload, this.services);
  }
}

export { SymbolsHandler };
