import { resolveBankAccountState } from './resolveBankAccountState';

const CLABE_BANAMEX = '002010077777777771';
const CLABE_UNKNOWN_BANK = '001010000000000002';

describe('resolveBankAccountState', () => {
  it('resolves the bank name for a valid CLABE in the catalog', () => {
    const state = resolveBankAccountState(CLABE_BANAMEX, 'MXN', '');

    expect(state).toMatchObject({
      isFormatValid: true,
      resolvedBankName: 'BANAMEX',
      showManualBankName: false,
      isBankNameValid: true,
      contractBankAccountNumber: CLABE_BANAMEX,
      contractBankName: 'BANAMEX',
    });
  });

  it('requests manual entry for a valid CLABE with no catalog match', () => {
    const state = resolveBankAccountState(CLABE_UNKNOWN_BANK, 'MXN', '');

    expect(state).toMatchObject({
      isFormatValid: true,
      resolvedBankName: null,
      showManualBankName: true,
      isBankNameValid: false,
      contractBankAccountNumber: CLABE_UNKNOWN_BANK,
      contractBankName: undefined,
    });
  });

  it('accepts a manual bank name of at least 3 characters', () => {
    const state = resolveBankAccountState(
      CLABE_UNKNOWN_BANK,
      'MXN',
      ' Mi Banco ',
    );

    expect(state.isBankNameValid).toBe(true);
    expect(state.contractBankName).toBe('Mi Banco');
  });

  it('rejects a manual bank name shorter than 3 characters', () => {
    const state = resolveBankAccountState(CLABE_UNKNOWN_BANK, 'MXN', 'ab');

    expect(state.isBankNameValid).toBe(false);
    expect(state.contractBankName).toBe('ab');
  });

  it('lets an edited bank name override the resolved catalog name', () => {
    const state = resolveBankAccountState(CLABE_BANAMEX, 'MXN', 'whatever');

    expect(state.showManualBankName).toBe(false);
    expect(state.contractBankName).toBe('whatever');
  });

  it('falls back to the catalog name when the edited value is blank', () => {
    const state = resolveBankAccountState(CLABE_BANAMEX, 'MXN', '   ');

    expect(state.isBankNameValid).toBe(true);
    expect(state.contractBankName).toBe('BANAMEX');
  });

  it('rejects editing a resolved bank name down to fewer than 3 chars', () => {
    const state = resolveBankAccountState(CLABE_BANAMEX, 'MXN', 'ab');

    expect(state.resolvedBankName).toBe('BANAMEX');
    expect(state.isBankNameValid).toBe(false);
    expect(state.contractBankName).toBe('ab');
  });

  it('returns an empty state for an invalid CLABE format', () => {
    const state = resolveBankAccountState('123', 'MXN', 'Mi Banco');

    expect(state).toMatchObject({
      isFormatValid: false,
      resolvedBankName: null,
      showManualBankName: false,
      isBankNameValid: true,
      contractBankAccountNumber: undefined,
      contractBankName: undefined,
    });
  });
});
