import { formatCentsUSD } from '@/lib/money';

// Display + matching helpers for bank transactions in the bill modal. Shared by
// the linked-transaction list, the unmatch dialogs, and the bulk-unmatch payee
// grouping.

interface TxLike {
  payee?: string | null;
  description?: string | null;
  memo?: string | null;
  posted_date?: string | null;
  transacted_at?: string | number | null;
}

export function fmtTransactionAmount(amount: Parameters<typeof formatCentsUSD>[0], currency = 'USD') {
  return formatCentsUSD(amount, { signed: true, currency });
}

export function transactionDate(tx: TxLike | null | undefined): string | null {
  return tx?.posted_date || String(tx?.transacted_at || '').slice(0, 10) || null;
}

export function transactionTitle(tx: TxLike | null | undefined): string {
  return tx?.payee || tx?.description || tx?.memo || 'Transaction';
}

export function normalizePayee(s: string | null | undefined): string {
  return (s || '').toLowerCase().replace(/[^a-z0-9]/g, '');
}

// Two payees are "similar" when one normalized name is a prefix of the other
// (min 3 chars) — the grouping used to find related matches to unmatch together.
export function isSimilarPayee(a: string | null | undefined, b: string | null | undefined): boolean {
  const na = normalizePayee(a);
  const nb = normalizePayee(b);
  const minLen = Math.min(na.length, nb.length);
  if (minLen < 3) return false;
  return na.startsWith(nb) || nb.startsWith(na);
}
