import { Injectable, Logger } from '@nestjs/common';
import { KafkaService } from './kafka.service';
import { DomainEvent } from '../../domain/events/domain-event.base';

/**
 * 事件发布服务
 *
 * 将领域事件发布到 Kafka
 */
@Injectable()
export class EventPublisherService {
  private readonly logger = new Logger(EventPublisherService.name);

  // Topic 映射
  private readonly topicMapping: Record<string, string> = {
    LeaderboardRefreshed: 'leaderboard.refreshed',
    LeaderboardConfigUpdated: 'leaderboard.config.updated',
    RankingChanged: 'leaderboard.ranking.changed',
  };

  constructor(private readonly kafkaService: KafkaService) {}

  /**
   * 发布领域事件
   */
  async publish(event: DomainEvent): Promise<void> {
    const topic = this.topicMapping[event.eventType];
    if (!topic) {
      this.logger.warn(`未知事件类型: ${event.eventType}`);
      return;
    }

    await this.kafkaService.publish(topic, {
      eventId: event.eventId,
      eventType: event.eventType,
      aggregateId: event.aggregateId,
      aggregateType: event.aggregateType,
      payload: event.toPayload(),
      occurredAt: event.occurredAt.toISOString(),
      version: event.version,
    });
  }

  /**
   * 批量发布领域事件
   */
  async publishAll(events: DomainEvent[]): Promise<void> {
    for (const event of events) {
      await this.publish(event);
    }
  }
}
