import axios from 'axios';
import { loadConfig } from '../config';
import { loadHybxConfig } from '@dbis/integration-foundation';

/** Production HYBX rail client for real settlement dispatch */
export class HybxProductionRail {
  private readonly baseUrl: string;
  private readonly apiKey: string;
  private readonly clientSecret: string;

  constructor() {
    const settlement = loadConfig();
    const allowLive =
      process.env.SETTLEMENT_ALLOW_HYBX_PRODUCTION === '1' ||
      settlement.production.allowHybxProduction;
    const cfg = loadHybxConfig({ testMode: !allowLive });
    if (cfg.environment === 'production' && !allowLive) {
      throw new Error(
        'HYBX production requires SETTLEMENT_ALLOW_HYBX_PRODUCTION=1 or production.allowHybxProduction in config',
      );
    }    this.baseUrl = cfg.baseUrl.replace(/\/$/, '');
    this.apiKey = cfg.apiKey;
    this.clientSecret = cfg.clientSecret;
  }

  async dispatchPayment(payload: {
    idempotencyKey: string;
    amount: string;
    currency: string;
    creditorIban: string;
    creditorBic?: string;
    beneficiaryName: string;
    remittanceInfo: string;
    rail: string;
  }): Promise<{ paymentId: string; status: string }> {
    const sidecar = process.env.HYBX_MIFOS_FINERACT_SIDECAR_URL?.replace(/\/$/, '');
    const url = sidecar ? `${sidecar}/v1/rtgs/payments` : `${this.baseUrl}/v1/payments`;
    const { data } = await axios.post(
      url,
      {
        externalId: payload.idempotencyKey,
        amount: payload.amount,
        currency: payload.currency,
        beneficiary: {
          iban: payload.creditorIban,
          bic: payload.creditorBic,
          name: payload.beneficiaryName,
        },
        remittanceInformation: payload.remittanceInfo,
        rail: payload.rail,
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': this.apiKey,
          Authorization: `Bearer ${this.clientSecret}`,
        },
        timeout: 120000,
      },
    );
    return {
      paymentId: String(data.paymentId ?? data.id ?? payload.idempotencyKey),
      status: String(data.status ?? 'DISPATCHED'),
    };
  }
}
