import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { EventPublisherPort } from '../../domain/ports/outbound/event-publisher.port';
import { RedisEventBus } from '@it0/events';

const DEFAULT_STREAM = 'agent-events';

/**
 * Implements EventPublisherPort using the shared RedisEventBus.
 * Publishes domain events to a Redis Stream for consumption by
 * other microservices (e.g., notification-service, audit-service).
 */
@Injectable()
export class EventPublisherService implements EventPublisherPort, OnModuleDestroy {
  private readonly logger = new Logger(EventPublisherService.name);
  private eventBus: RedisEventBus | null = null;

  constructor(private readonly configService: ConfigService) {
    this.initEventBus();
  }

  private initEventBus(): void {
    const redisUrl = this.configService.get<string>(
      'REDIS_URL',
      'redis://localhost:6379',
    );

    try {
      this.eventBus = new RedisEventBus(redisUrl);
      this.logger.log('EventPublisherService connected to Redis');
    } catch (err: any) {
      this.logger.error(
        `Failed to connect EventPublisherService to Redis: ${err.message}`,
      );
    }
  }

  async publish(
    eventType: string,
    payload: Record<string, unknown>,
  ): Promise<void> {
    if (!this.eventBus) {
      this.logger.warn(
        `EventBus not initialized, dropping event: ${eventType}`,
      );
      return;
    }

    const stream = this.configService.get<string>(
      'AGENT_EVENT_STREAM',
      DEFAULT_STREAM,
    );

    try {
      await this.eventBus.publish(stream, {
        eventType,
        timestamp: new Date().toISOString(),
        ...payload,
      });
      this.logger.debug(`Published event: ${eventType}`);
    } catch (err: any) {
      this.logger.error(
        `Failed to publish event ${eventType}: ${err.message}`,
      );
    }
  }

  async onModuleDestroy(): Promise<void> {
    if (this.eventBus) {
      await this.eventBus.disconnect();
      this.logger.log('EventPublisherService disconnected from Redis');
    }
  }
}
