import { Module } from "@nestjs/common";
import { HttpModule } from "@nestjs/axios";
import { ConfigService } from "@nestjs/config";
import { RabbitMQModule } from "@golevelup/nestjs-rabbitmq";
import { DynamicModule } from "@nestjs/common";
import {
  PAYMENT_EVENTS_DLX,
  PAYMENT_EVENTS_EXCHANGE,
  PAYMENT_QUEUES,
  PaymentService,
  paymentServiceBindingPattern,
} from "@edr/types";
import { PaymentsController } from "./payments.controller";
import { PaymentsService } from "./payments.service";
import { InternalPaymentsController } from "./internal-payments.controller";
import { PaymentClientService } from "./payment-client.service";
import { PaymentEventsConsumer } from "./payment-events.consumer";
import { ServiceAuthGuard } from "../../common/guards/service-auth.guard";
import { SeatsModule } from "../seats/seats.module";
import { TicketsModule } from "../tickets/tickets.module";

const PASSENGER_QUEUE = PAYMENT_QUEUES[PaymentService.PASSENGER];

function rabbitMQImport(): DynamicModule[] {
  if (!process.env.PAYMENT_RABBITMQ_URL) return [];
  return [
    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 } },
        ],
        queues: [
          {
            name: PASSENGER_QUEUE.dlq,
            exchange: PAYMENT_EVENTS_DLX,
            routingKey: paymentServiceBindingPattern(PaymentService.PASSENGER),
            options: { durable: true },
          },
        ],
        prefetchCount: config.get<number>("rabbitmq.prefetch") ?? 10,
        connectionInitOptions: { wait: false },
      }),
    }),
  ];
}

@Module({
  imports: [
    SeatsModule,
    TicketsModule,
    HttpModule.register({ timeout: 10_000 }),
    ...rabbitMQImport(),
  ],
  controllers: [PaymentsController, InternalPaymentsController],
  providers: [
    PaymentsService,
    PaymentClientService,
    PaymentEventsConsumer,
    ServiceAuthGuard,
  ],
})
export class PaymentsModule {}
