import { customerPayState, customerPosition } from './customer-position';

describe('customerPosition / customerPayState', () => {
  describe('price cuts on bills the customer has not fully paid (prod 2026-10-20)', () => {
    it.each([
      // booking, billed, collected, refund lines, refunded → state, owes
      ['BK-437675', 5086, 0, 132, 0, 'UNPAID', 4954],
      ['BK-048472', 7742, 3670, 442, 0, 'PARTIAL', 3630],
      ['BK-128243', 1560, 0, 1090, 0, 'UNPAID', 470],
      ['MT-993598', 3795, 0, 123, 0, 'UNPAID', 3672],
    ])('%s is not a refund', (_bk, billed, collected, refundLines, refunded, state, owes) => {
      const p = customerPosition({ billed, collected, refundLines, refunded });
      expect(p.refundDue).toBe(0);
      expect(p.outstanding).toBe(owes);
      expect(customerPayState(p)).toBe(state);
    });
  });

  describe('real refunds', () => {
    it('is due when the customer paid more than the new price', () => {
      // Paid 1000 in full, price then cut by 200.
      const p = customerPosition({ billed: 1000, collected: 1000, refundLines: 200, refunded: 0 });
      expect(p).toEqual({ netPrice: 800, netReceived: 1000, outstanding: 0, refundDue: 200 });
      expect(customerPayState(p)).toBe('REFUND_DUE');
    });

    it('only the overpaid part is due', () => {
      // Paid 900 of 1000, price cut by 200 → 100 back.
      const p = customerPosition({ billed: 1000, collected: 900, refundLines: 200, refunded: 0 });
      expect(p.refundDue).toBe(100);
      expect(customerPayState(p)).toBe('REFUND_DUE');
    });

    it('clears once the refund is paid out', () => {
      const p = customerPosition({
        billed: 1000,
        collected: 1000,
        refundLines: 200,
        refunded: 200,
      });
      expect(p).toEqual({ netPrice: 800, netReceived: 800, outstanding: 0, refundDue: 0 });
      expect(customerPayState(p)).toBe('PAID');
    });
  });

  describe('no refund lines', () => {
    it.each([
      [0, 0, 'UNPAID'],
      [1000, 0, 'UNPAID'],
      [1000, 400, 'PARTIAL'],
      [1000, 1000, 'PAID'],
      [1000, 999.996, 'PAID'],
    ])('billed %s, collected %s → %s', (billed, collected, state) => {
      const p = customerPosition({ billed, collected, refundLines: 0, refunded: 0 });
      expect(customerPayState(p)).toBe(state);
    });
  });
});
