import { Injectable, Logger, Inject, OnModuleInit } from '@nestjs/common';
import { ClientKafka } from '@nestjs/microservices';

/**
 * Kafka 事件发布服务
 * 直接发布事件到 Kafka（用于非 Outbox 场景）
 */
@Injectable()
export class EventPublisherService implements OnModuleInit {
  private readonly logger = new Logger(EventPublisherService.name);

  constructor(
    @Inject('KAFKA_SERVICE')
    private readonly kafkaClient: ClientKafka,
  ) {}

  async onModuleInit() {
    await this.kafkaClient.connect();
    this.logger.log('Kafka EventPublisher connected');
  }

  /**
   * 发布事件到指定 topic
   */
  async publish(topic: string, key: string, payload: Record<string, unknown>): Promise<void> {
    try {
      this.kafkaClient.emit(topic, {
        key,
        value: JSON.stringify(payload),
      });
      this.logger.debug(`Published event to ${topic} with key ${key}`);
    } catch (error) {
      this.logger.error(`Failed to publish to ${topic}: ${error}`);
      throw error;
    }
  }
}
