import { type CurrencyCode } from '../types';

import { getBankNameFromBankAccountNumber } from './getBankNameFromBankAccountNumber';
import { validateBankAccountNumber } from './validateBankAccountNumber';

export type BankAccountState = {
  isFormatValid: boolean;
  resolvedBankName: string | null;
  showManualBankName: boolean;
  isBankNameValid: boolean;
  contractBankAccountNumber?: string;
  contractBankName?: string;
};

export function resolveBankAccountState(
  bankAccountNumber: string,
  currency: CurrencyCode,
  manualBankName: string,
): BankAccountState {
  const isFormatValid = validateBankAccountNumber(bankAccountNumber);
  const resolvedBankName =
    isFormatValid && currency === 'MXN'
      ? getBankNameFromBankAccountNumber(bankAccountNumber, currency)
      : null;
  const showManualBankName = isFormatValid && resolvedBankName === null;

  const trimmedManual = manualBankName.trim();
  const effectiveBankName = trimmedManual || resolvedBankName || '';
  const isBankNameValid = !isFormatValid || effectiveBankName.length >= 3;

  const contractBankAccountNumber = isFormatValid
    ? bankAccountNumber
    : undefined;
  const contractBankName = isFormatValid
    ? effectiveBankName || undefined
    : undefined;

  return {
    isFormatValid,
    resolvedBankName,
    showManualBankName,
    isBankNameValid,
    contractBankAccountNumber,
    contractBankName,
  };
}
