/* ------------------------------------------------------------------------------------------------
 * Payment event messaging contract (RabbitMQ)
 *
 * The single source of truth for the broker topology shared between the payment microservice
 * (publisher) and the domain apps (consumers). Both sides import these constants/helpers so the
 * exchange name, routing keys, and queue names can never drift apart.
 *
 * Topology (see docs/payment-service/rabbitmq/):
 *   exchange  payment.events       (topic, durable)   ← every payment event is published here
 *   exchange  payment.events.dlx   (topic, durable)   ← dead-letter for events a consumer rejects
 *   routing   payment.<service>.<outcome>             e.g. payment.passenger.succeeded
 *   queue     <service>.payment-events                bound to payment.<service>.*
 *   queue     <service>.payment-events.dlq            dead-letter queue (bound on the dlx)
 * ---------------------------------------------------------------------------------------------- */

import { PaymentEventType, PaymentService } from "./payments";

/** Topic exchange every payment event is published to. */
export const PAYMENT_EVENTS_EXCHANGE = "payment.events";

/** Dead-letter exchange for payment events a consumer could not process (poison messages). */
export const PAYMENT_EVENTS_DLX = "payment.events.dlx";

/**
 * Routing key for a payment event: `payment.<service>.<outcome>`.
 * e.g. `payment.passenger.succeeded`, `payment.freight.failed`.
 */
export function paymentRoutingKey(
  service: PaymentService,
  eventType: PaymentEventType,
): string {
  // "payment.succeeded" -> "succeeded", "payment.failed" -> "failed"
  const outcome = eventType.split(".")[1];
  return `payment.${service.toLowerCase()}.${outcome}`;
}

/** Binding pattern a service's queue uses so it receives only its own events. */
export function paymentServiceBindingPattern(service: PaymentService): string {
  return `payment.${service.toLowerCase()}.*`;
}

/** Durable queue names per owning service: the main work queue and its dead-letter queue. */
export const PAYMENT_QUEUES: Record<
  PaymentService,
  { main: string; dlq: string }
> = {
  [PaymentService.PASSENGER]: {
    main: "passenger.payment-events",
    dlq: "passenger.payment-events.dlq",
  },
  [PaymentService.FREIGHT]: {
    main: "freight.payment-events",
    dlq: "freight.payment-events.dlq",
  },
};
