import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { firstValueFrom } from 'rxjs';
import { NotificationPort, SendNotificationParams } from '../../domain/ports/outbound/notification.port';

@Injectable()
export class CommClientService implements NotificationPort {
  private readonly logger = new Logger(CommClientService.name);
  private readonly baseUrl: string;

  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {
    this.baseUrl = this.configService.get<string>(
      'COMM_SERVICE_URL',
      'http://localhost:3004',
    );
  }

  async sendNotification(params: SendNotificationParams): Promise<void> {
    this.logger.log(
      `Sending notification via ${params.channel} for tenant ${params.tenantId} (priority: ${params.priority})`,
    );

    try {
      await firstValueFrom(
        this.httpService.post(`${this.baseUrl}/api/v1/comm/notifications`, {
          tenantId: params.tenantId,
          channel: params.channel,
          content: params.content,
          priority: params.priority,
          contactIds: params.contactIds,
        }),
      );

      this.logger.log(`Notification sent successfully via ${params.channel}`);
    } catch (error: any) {
      this.logger.error(
        `Failed to send notification via ${params.channel}: ${error.message}`,
      );
      throw error;
    }
  }
}
