import type { SwiftMessageKind, TradeFinanceInstrument } from './types';

/** SWIFT / trade-finance instrument routing */
export const INSTRUMENT_ROUTING: Record<
  TradeFinanceInstrument,
  { swift: SwiftMessageKind[]; glDebit: string; glCredit: string }
> = {
  SBLC: { swift: ['MT103', 'MT202'], glDebit: '1410', glCredit: '2100' },
  DLC: { swift: ['MT103', 'MT102'], glDebit: '1410', glCredit: '1000' },
  BG: { swift: ['MT103'], glDebit: '1410', glCredit: '2100' },
  LS: { swift: ['MT102', 'MT103'], glDebit: '1000', glCredit: '2200' },
};

export function resolveInstrumentGl(
  instrument: TradeFinanceInstrument,
): { debitGl: string; creditGl: string; swiftKinds: SwiftMessageKind[] } {
  const r = INSTRUMENT_ROUTING[instrument];
  return { debitGl: r.glDebit, creditGl: r.glCredit, swiftKinds: r.swift };
}

export function isIbanValid(iban: string): boolean {
  const normalized = iban.replace(/\s/g, '').toUpperCase();
  if (!/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/.test(normalized)) return false;
  const rearranged = normalized.slice(4) + normalized.slice(0, 4);
  const numeric = rearranged.replace(/[A-Z]/g, (c) => String(c.charCodeAt(0) - 55));
  let remainder = 0;
  for (const ch of numeric) {
    remainder = (remainder * 10 + parseInt(ch, 10)) % 97;
  }
  return remainder === 1;
}
