import { Injectable, Logger } from '@nestjs/common';
import { Nack, RabbitSubscribe } from '@golevelup/nestjs-rabbitmq';
import {
  PAYMENT_EVENTS_DLX,
  PAYMENT_EVENTS_EXCHANGE,
  PAYMENT_QUEUES,
  PaymentEvent,
  PaymentService,
  paymentServiceBindingPattern,
} from '@edr/types';
import { PaymentEventDto } from './internal-payments.dto';
import { PaymentsService } from './payments.service';

const PASSENGER_QUEUE = PAYMENT_QUEUES[PaymentService.PASSENGER];

@Injectable()
export class PaymentEventsConsumer {
  private readonly logger = new Logger(PaymentEventsConsumer.name);

  constructor(private readonly paymentsService: PaymentsService) {}

  @RabbitSubscribe({
    exchange: PAYMENT_EVENTS_EXCHANGE,
    routingKey: paymentServiceBindingPattern(PaymentService.PASSENGER), // payment.passenger.*
    queue: PASSENGER_QUEUE.main,
    queueOptions: {
      durable: true,
      deadLetterExchange: PAYMENT_EVENTS_DLX,
    },
  })
  async handle(event: PaymentEvent): Promise<Nack | void> {
    try {
      const result = await this.paymentsService.handlePaymentEvent(
        event as unknown as PaymentEventDto,
      );
      this.logger.log(
        `processed ${event.eventType} (${event.eventId}) ref=${event.referenceId}: ${JSON.stringify(result)}`,
      );
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      this.logger.error(
        `DEAD-LETTERING ${event.eventType} (${event.eventId}) ref=${event.referenceId}: ${message}`,
      );
      return new Nack(false);
    }
  }
}
