
const extractReferenceValue = (reference: string, key: string): string => {
  if (!reference) {
    return '';
  }

  // Capture everything after KEY= until the next XXX= block or end of string
  const regex = new RegExp(`${key}=([\\s\\S]*?)(?=\\s+[A-Z]{2,}=|$)`);
  const match = reference.match(regex);

  if (!match) {
    return '';
  }

  let value = match[1].trim();

  value = value.trim();

  // Remove NOTPROVIDED if present
  value = value.replace(/NOTPROVIDED/gi, '').trim();

  // Collapse multiple spaces (incl. tabs) into a single space
  value = value.replace(/\s{2,}/g, ' ');

  return value;
};

export const convertBankReferenceToTransactionReference = (rawReference: string) => {
  // If reference is empty/null → return empty string
  if (!rawReference || !rawReference.trim()) {
    return '';
  }

  const org = extractReferenceValue(rawReference, 'ORG');
  const bnf = extractReferenceValue(rawReference, 'BNF');
  const obi = extractReferenceValue(rawReference, 'OBI');

  // If none of the required keys were found → return original reference as-is
  if (!org && !bnf && !obi) {
    return rawReference;
  }

  return `${org || ''} : ${bnf || ''} : ${obi || ''}`;
};
