import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { ClientsModule, Transport } from "@nestjs/microservices";

import { NotificationsService } from "./notifications.service";
import { SmsClientService } from "./sms-client.service";
import { EmailClientService } from "./email-client.service";
import { EmailNotificationStrategy } from "./strategies/notification.email.strategy";
import { SmsNotificationStrategy } from "./strategies/notification.sms.strategy";

// Fall back to a sane broker URL so an unset RABBITMQ_URL can't produce
// `urls: [undefined]` (which crashes amqp-connection-manager on 'heartbeat').
const RABBITMQ_URL =
  process.env.RABBITMQ_URL ?? process.env.PAYMENT_RABBITMQ_URL ?? "amqp://localhost:5672";

@Module({
  imports: [
    ConfigModule,
    ClientsModule.register([
      {
        name: "SMS_SERVICE",
        transport: Transport.RMQ,
        options: {
          urls: [RABBITMQ_URL],
          queue: process.env.SMS_QUEUE ?? "sms_queue",
          queueOptions: { durable: true },
        },
      },
      {
        name: "EMAIL_SERVICE",
        transport: Transport.RMQ,
        options: {
          urls: [RABBITMQ_URL],
          queue: process.env.EMAIL_QUEUE ?? "email_queue",
          queueOptions: { durable: true },
        },
      },
    ]),
  ],
  controllers: [],
  providers: [
    EmailNotificationStrategy,
    SmsNotificationStrategy,
    NotificationsService,
    SmsClientService,
    EmailClientService,
  ],
  exports: [NotificationsService, SmsClientService, EmailClientService],
})
export class NotificationsModule {}
