import { Injectable, OnModuleInit, Logger } from '@nestjs/common';
import { PrePlantingCdcConsumerService } from '../../infrastructure/kafka/pre-planting-cdc-consumer.service';
import { PrePlantingOrderSyncedHandler, PrePlantingOrderSyncResult } from './pre-planting-order-synced.handler';
import { PrePlantingPositionSyncedHandler } from './pre-planting-position-synced.handler';
import { PrePlantingMergeSyncedHandler } from './pre-planting-merge-synced.handler';
import { PrePlantingMergeSyncResult } from '../services/pre-planting-contribution.service';

/**
 * 预种 CDC 事件分发器
 *
 * [2026-02-17] 新增：将预种 CDC 事件路由到对应的处理器
 *
 * === 与现有 CDCEventDispatcher 的关系 ===
 * - 完全独立的实例，不与现有 CDCEventDispatcher 共享任何状态
 * - 使用独立的 PrePlantingCdcConsumerService（独立 consumer group、独立 topics）
 * - 注册不同的 handler：预种订单 + 预种持仓（不处理 user_accounts / referral_relationships）
 *
 * === 对现有系统的影响 ===
 * - 零影响。现有 CDCEventDispatcher 照常运行。
 * - 两个 dispatcher 各自独立启动、独立消费、互不干扰。
 */
@Injectable()
export class PrePlantingCdcDispatcher implements OnModuleInit {
  private readonly logger = new Logger(PrePlantingCdcDispatcher.name);

  constructor(
    private readonly cdcConsumer: PrePlantingCdcConsumerService,
    private readonly orderHandler: PrePlantingOrderSyncedHandler,
    private readonly positionHandler: PrePlantingPositionSyncedHandler,
    private readonly mergeHandler: PrePlantingMergeSyncedHandler,
  ) {}

  async onModuleInit() {
    // 注册预种订单表 handler（带后置回调：事务提交后计算算力）
    this.cdcConsumer.registerHandler<PrePlantingOrderSyncResult | null>(
      'pre_planting_orders',
      this.orderHandler.handle.bind(this.orderHandler),
      this.orderHandler.calculateAfterCommit.bind(this.orderHandler),
    );

    // 注册预种持仓表 handler（无后置回调：纯同步，不触发算力计算）
    this.cdcConsumer.registerHandler(
      'pre_planting_positions',
      this.positionHandler.handle.bind(this.positionHandler),
    );

    // 注册预种合成树 handler（带后置回调：事务提交后执行算力切换）
    this.cdcConsumer.registerHandler<PrePlantingMergeSyncResult | null>(
      'pre_planting_merges',
      this.mergeHandler.handle.bind(this.mergeHandler),
      this.mergeHandler.swapAfterCommit.bind(this.mergeHandler),
    );

    // 非阻塞启动 CDC 消费者
    this.cdcConsumer.start()
      .then(() => {
        this.logger.log(
          '[PRE-PLANTING-CDC] Dispatcher started with handlers: ' +
          'pre_planting_orders, pre_planting_positions, pre_planting_merges',
        );
      })
      .catch((error) => {
        this.logger.error('[PRE-PLANTING-CDC] Failed to start dispatcher', error);
        // 不抛出错误，允许服务在没有预种 CDC 的情况下启动
      });
  }
}
