import {
  cashInBankUsdFromGlRows,
  evaluateSupplyNostroMatch,
  externalNostroCashFromGlRows,
  resetCashInBankAuditCache,
} from './omnl-cash-in-bank-audit';

describe('externalNostroCashFromGlRows', () => {
  it('uses GL 13010 Dr only — excludes reserve GL 1000', () => {
    const { cashInBankUsd, legs } = externalNostroCashFromGlRows(
      [
        { glCode: '13010', name: 'Nostro USD', side: 'Dr', amount: '999998500.00' },
        { glCode: '1000', name: 'Reserve asset', side: 'Dr', amount: '900000000000.00' },
      ],
      '13010',
    );

    expect(cashInBankUsd).toBeCloseTo(999_998_500, 0);
    expect(legs).toHaveLength(1);
    expect(legs[0]?.glCode).toBe('13010');
  });
});

describe('cashInBankUsdFromGlRows', () => {
  it('sums Dr balances on all listed nostro GL codes', () => {
    const { cashInBankUsd, legs } = cashInBankUsdFromGlRows(
      [
        { glCode: '13010', name: 'Nostro USD', side: 'Dr', amount: '500000000.00' },
        { glCode: '1000', name: 'Reserve asset', side: 'Dr', amount: '250000000.00' },
      ],
      ['13010', '1000'],
    );

    expect(cashInBankUsd).toBeCloseTo(750_000_000, 0);
    expect(legs).toHaveLength(2);
  });
});

describe('evaluateSupplyNostroMatch', () => {
  it('matches when total supply USD equals 1.2× external nostro', () => {
    const match = evaluateSupplyNostroMatch({
      totalSupplyUsd: 1_200_000_000,
      externalNostroCashUsd: 1_000_000_000,
      multiplier: 1.2,
      toleranceBps: 100,
    });

    expect(match.status).toBe('matched');
    expect(match.expectedSupplyUsd).toBeCloseTo(1_200_000_000, 0);
    expect(match.headOfficeId).toBe(1);
    expect(match.formula).toContain('1.2');
  });

  it('breaks when total supply deviates beyond tolerance', () => {
    const match = evaluateSupplyNostroMatch({
      totalSupplyUsd: 147_500_000_000,
      externalNostroCashUsd: 999_998_500,
      multiplier: 1.2,
      toleranceBps: 100,
    });

    expect(match.status).toBe('break');
    expect(match.expectedSupplyUsd).toBeCloseTo(1_199_998_200, 0);
  });
});

describe('resetCashInBankAuditCache', () => {
  it('clears cached snapshot without throwing', () => {
    expect(() => resetCashInBankAuditCache()).not.toThrow();
  });
});
