import { Injectable, OnModuleInit, Logger } from '@nestjs/common';
import { KafkaService } from './kafka.service';
import { EachMessagePayload } from 'kafkajs';

/**
 * 事件消费服务
 *
 * 订阅并处理来自其他服务的事件
 */
@Injectable()
export class EventConsumerService implements OnModuleInit {
  private readonly logger = new Logger(EventConsumerService.name);

  // 订阅的 topics
  private readonly subscribedTopics = [
    'referral.statistics.updated',  // 团队统计更新事件
  ];

  constructor(private readonly kafkaService: KafkaService) {}

  async onModuleInit() {
    await this.kafkaService.subscribe(
      this.subscribedTopics,
      this.handleMessage.bind(this),
    );
  }

  private async handleMessage(payload: EachMessagePayload): Promise<void> {
    const { topic, message } = payload;
    const value = message.value?.toString();

    if (!value) {
      return;
    }

    try {
      const event = JSON.parse(value);
      this.logger.debug(`收到事件: ${topic}`, event);

      switch (topic) {
        case 'referral.statistics.updated':
          await this.handleTeamStatisticsUpdated(event);
          break;
        default:
          this.logger.warn(`未处理的 topic: ${topic}`);
      }
    } catch (error) {
      this.logger.error(`处理消息失败: ${topic}`, error);
    }
  }

  /**
   * 处理团队统计更新事件
   *
   * 当团队统计数据更新时，标记需要刷新榜单
   */
  private async handleTeamStatisticsUpdated(event: any): Promise<void> {
    this.logger.log('收到团队统计更新事件，榜单将在下次定时任务中刷新');
    // TODO: 可以实现即时刷新或标记刷新标志
  }
}
