import { BadRequestException } from '@nestjs/common';
import { addonSupplierCost, computeAddonChange } from './addon-pax';

describe('computeAddonChange', () => {
  const base = { adults: 2, children: 0 };
  const none = { adults: 0, children: 0 };

  it('no change when within the booked pax (partial cancel stays as-is)', () => {
    expect(
      computeAddonChange({
        base,
        effective: { adults: 1, children: 0 },
        oldAddon: none,
        oldBilled: 0,
      }),
    ).toBeNull();
  });

  it('bills the confirmed charge for an extra adult', () => {
    expect(
      computeAddonChange({
        base,
        effective: { adults: 3, children: 0 },
        oldAddon: none,
        oldBilled: 0,
        charge: 150,
      }),
    ).toEqual({ addon: { adults: 1, children: 0 }, billedDelta: 150, added: 1, removed: 0 });
  });

  it('refuses an add-on without a charge (no complimentary)', () => {
    expect(() =>
      computeAddonChange({
        base,
        effective: { adults: 3, children: 0 },
        oldAddon: none,
        oldBilled: 0,
      }),
    ).toThrow(BadRequestException);
  });

  it('refunds pro-rata when add-ons are reduced', () => {
    expect(
      computeAddonChange({
        base,
        effective: { adults: 3, children: 0 },
        oldAddon: { adults: 2, children: 0 },
        oldBilled: 300,
      }),
    ).toEqual({ addon: { adults: 1, children: 0 }, billedDelta: -150, added: 0, removed: 1 });
  });
});

describe('addonSupplierCost', () => {
  const oldPax = { adults: 1, children: 1 };
  const rates = { adult: 177, child: 142 };

  it('adds each extra pax at its own age cost', () => {
    // 300 for 1A+1C, +2 adults at 177 → 654 (not the per-head 600)
    expect(
      addonSupplierCost({ lineCost: 300, oldPax, newPax: { adults: 3, children: 1 }, rates }),
    ).toBe(654);
    expect(
      addonSupplierCost({ lineCost: 300, oldPax, newPax: { adults: 1, children: 2 }, rates }),
    ).toBe(442);
  });

  it('takes the age cost off when pax are removed', () => {
    expect(
      addonSupplierCost({
        lineCost: 654,
        oldPax: { adults: 3, children: 1 },
        newPax: { adults: 2, children: 1 },
        rates,
      }),
    ).toBe(477);
  });

  it('falls back to the average per-pax cost when an age has no rate', () => {
    expect(
      addonSupplierCost({
        lineCost: 300,
        oldPax,
        newPax: { adults: 1, children: 2 },
        rates: { adult: 177 },
      }),
    ).toBe(450);
  });

  it('never goes below 0', () => {
    expect(
      addonSupplierCost({ lineCost: 100, oldPax, newPax: { adults: 0, children: 0 }, rates }),
    ).toBe(0);
  });
});
