import { Module } from "@nestjs/common";
import { HttpModule } from "@nestjs/axios";
import { ConfigService } from "@nestjs/config";
import { TypeOrmModule } from "@nestjs/typeorm";
import { RabbitMQModule } from "@golevelup/nestjs-rabbitmq";
import { PAYMENT_EVENTS_DLX, PAYMENT_EVENTS_EXCHANGE } from "@edr/types";
import { isRabbitPublisher } from "../../config/rabbitmq.config";
import { NotificationOutbox } from "./entities/notification-outbox.entity";
import { OutboxRelayService } from "./outbox-relay.service";
import { OutboxRepository } from "./outbox.repository";
import { HttpPaymentEventPublisher } from "./publisher/http-payment-event-publisher";
import { PAYMENT_EVENT_PUBLISHER } from "./publisher/payment-event-publisher";
import { RabbitMqPaymentEventPublisher } from "./publisher/rabbitmq-payment-event-publisher";

const rabbitImports = isRabbitPublisher()
  ? [
      RabbitMQModule.forRootAsync({
        inject: [ConfigService],
        useFactory: (config: ConfigService) => ({
          uri: config.get<string>("rabbitmq.url") as string,
          exchanges: [
            {
              name: PAYMENT_EVENTS_EXCHANGE,
              type: "topic",
              options: { durable: true },
            },
            {
              name: PAYMENT_EVENTS_DLX,
              type: "topic",
              options: { durable: true },
            },
          ],
          connectionInitOptions: { wait: false },
        }),
      }),
    ]
  : [];

@Module({
  imports: [
    TypeOrmModule.forFeature([NotificationOutbox]),
    HttpModule,
    ...rabbitImports,
  ],
  providers: [
    OutboxRepository,
    OutboxRelayService,
    {
      provide: PAYMENT_EVENT_PUBLISHER,
      useClass: isRabbitPublisher()
        ? RabbitMqPaymentEventPublisher
        : HttpPaymentEventPublisher,
    },
  ],
  exports: [OutboxRepository],
})
export class OutboxModule {}
