import axios from 'axios';

export async function forwardSwiftToListener(raw: string): Promise<{ accepted: boolean }> {
  const url = (process.env.SWIFT_LISTENER_URL || 'http://192.168.11.114:8788').replace(/\/$/, '');
  const token = process.env.SWIFT_LISTENER_WEBHOOK_TOKEN || '';
  const headers: Record<string, string> = { 'Content-Type': 'text/plain' };
  if (token) headers.Authorization = `Bearer ${token}`;

  await axios.post(`${url}/inbound`, raw, { headers, timeout: 60000 });
  return { accepted: true };
}

export function buildMt103Stub(fields: {
  senderRef: string;
  currency: string;
  amount: string;
  valueDate: string;
  orderingCustomer: string;
  beneficiary: string;
  iban: string;
  bic?: string;
  remittance: string;
}): string {
  const bicLine = fields.bic ? `:57A:${fields.bic}\n` : '';
  return `{1:F01OMNLUS33XXXX0000000000}{2:I103BANKUS33XXXXN}{4:
:20:${fields.senderRef}
:23B:CRED
:32A:${fields.valueDate.replace(/-/g, '').slice(2)}${fields.currency}${fields.amount.replace('.', ',')}
:50K:${fields.orderingCustomer}
:59:/${fields.iban}
${fields.beneficiary}
${bicLine}:70:${fields.remittance}
:71A:OUR
-}`;
}

export function buildMt102Stub(fields: {
  senderRef: string;
  currency: string;
  amount: string;
  valueDate: string;
  orderingInstitution: string;
  beneficiary: string;
  iban: string;
  remittance: string;
}): string {
  return `{1:F01OMNLUS33XXXX0000000000}{2:I102BANKUS33XXXXN}{4:
:20:${fields.senderRef}
:21:NONREF
:32B:${fields.currency}${fields.amount.replace('.', ',')}
:50A:${fields.orderingInstitution}
:59:/${fields.iban}
${fields.beneficiary}
:70:${fields.remittance}
-}`;
}
