import { Injectable, OnModuleInit, OnModuleDestroy, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Kafka, Producer, logLevel } from 'kafkajs';

@Injectable()
export class EventPublisherService implements OnModuleInit, OnModuleDestroy {
  private readonly logger = new Logger(EventPublisherService.name);
  private kafka: Kafka;
  private producer: Producer;
  private readonly topic: string;
  private readonly enabled: boolean;

  constructor(private readonly configService: ConfigService) {
    this.enabled = this.configService.get<string>('KAFKA_ENABLED', 'false') === 'true';

    if (this.enabled) {
      this.kafka = new Kafka({
        clientId: 'presence-service',
        brokers: this.configService.get<string>('KAFKA_BROKERS', 'localhost:9092').split(','),
        logLevel: logLevel.WARN,
      });
      this.producer = this.kafka.producer();
    }

    this.topic = this.configService.get<string>('KAFKA_TOPIC_ANALYTICS', 'analytics-events');
  }

  async onModuleInit(): Promise<void> {
    if (this.enabled) {
      await this.producer.connect();
      this.logger.log('Kafka producer connected');
    } else {
      this.logger.log('Kafka is disabled');
    }
  }

  async onModuleDestroy(): Promise<void> {
    if (this.enabled) {
      await this.producer.disconnect();
      this.logger.log('Kafka producer disconnected');
    }
  }

  async publish(eventType: string, payload: unknown): Promise<void> {
    if (!this.enabled) {
      this.logger.debug(`Kafka disabled, skipping event: ${eventType}`);
      return;
    }

    try {
      await this.producer.send({
        topic: this.topic,
        messages: [
          {
            key: eventType,
            value: JSON.stringify({
              eventType,
              payload,
              occurredAt: new Date().toISOString(),
            }),
          },
        ],
      });
    } catch (error) {
      this.logger.error(`Failed to publish event ${eventType}`, error);
    }
  }
}
