import { describe, expect, it } from 'vitest';
import { followedFigureOn, followSegments, nextPeriodStart } from './standard-billing';
import type { StandardChargeRow } from './standard-charge.resolution';

const D = (iso: string): Date => new Date(`${iso}T00:00:00.000Z`);
const iso = (d: Date | null) => (d ? d.toISOString().slice(0, 10) : null);

let seq = 0;
const row = (unitId: string | null, amount: string, effectiveFrom: string, chargeTypeId = 'MGMT'): StandardChargeRow => ({
  id: `sc${++seq}`,
  unitId,
  chargeTypeId,
  amount,
  effectiveFrom: D(effectiveFrom),
  createdAt: D('2020-01-01'),
});
const brief = (segs: ReturnType<typeof followSegments>) => segs.map((s) => `${iso(s.start)}→${iso(s.end)} ${s.amount ?? '-'} ${s.changed.length}`);

describe('nextPeriodStart', () => {
  it('is the day itself on a period start, the next 1st otherwise, for a monthly charge', () => {
    expect(iso(nextPeriodStart(D('2026-01-15'), 1, D('2026-06-01')))).toBe('2026-06-01');
    expect(iso(nextPeriodStart(D('2026-01-15'), 1, D('2026-06-15')))).toBe('2026-07-01');
    expect(iso(nextPeriodStart(D('2026-01-15'), 1, D('2026-12-20')))).toBe('2027-01-01');
  });
  it('counts a quarterly charge’s periods from the tenancy’s first month', () => {
    // Started February: periods open in February, May, August, November.
    expect(iso(nextPeriodStart(D('2026-02-15'), 3, D('2026-03-10')))).toBe('2026-05-01');
    expect(iso(nextPeriodStart(D('2026-02-15'), 3, D('2026-05-01')))).toBe('2026-05-01');
    expect(iso(nextPeriodStart(D('2026-02-15'), 3, D('2026-05-02')))).toBe('2026-08-01');
    expect(iso(nextPeriodStart(D('2026-02-15'), 3, D('2026-12-01')))).toBe('2027-02-01');
  });
});

describe('followSegments', () => {
  const property = [row(null, '2400', '2025-01-01'), row(null, '2640', '2026-12-01')];

  it('splits at the effective date for a rule prorated by day', () => {
    const segs = followSegments({ history: property, chargeTypeId: 'MGMT', unitIds: ['A'], from: D('2026-01-01'), to: null });
    expect(brief(segs)).toEqual(['2026-01-01→2026-11-30 2400.00 0', '2026-12-01→null 2640.00 1']);
    expect(segs[1].changed).toEqual([property[1].id]);
  });

  it('takes a mid-month change from the next period for a whole-month rule', () => {
    const mid = [row(null, '2400', '2025-01-01'), row(null, '2640', '2026-12-15')];
    const segs = followSegments({
      history: mid, chargeTypeId: 'MGMT', unitIds: ['A'], from: D('2026-01-01'), to: null,
      effectiveOn: (d) => nextPeriodStart(D('2026-01-01'), 1, d),
    });
    expect(brief(segs)).toEqual(['2026-01-01→2026-12-31 2400.00 0', '2027-01-01→null 2640.00 1']);
  });

  it('adds up the units of a whole-lease rule, a unit’s own figure beating the property’s', () => {
    const h = [row(null, '1000', '2025-01-01'), row('B', '1500', '2025-01-01'), row(null, '1100', '2026-07-01')];
    const segs = followSegments({ history: h, chargeTypeId: 'MGMT', unitIds: ['A', 'B'], from: D('2026-01-01'), to: null });
    // A follows the property 1000 → 1100; B keeps its own 1500.
    expect(brief(segs)).toEqual(['2026-01-01→2026-06-30 2500.00 0', '2026-07-01→null 2600.00 1']);
  });

  it('bills the units that have a figure when another on the same rule has none', () => {
    const h = [row('A', '1000', '2025-01-01'), row('B', '1500', '2025-01-01'), row('C', '400', '2026-05-01')];
    const segs = followSegments({ history: h, chargeTypeId: 'MGMT', unitIds: ['A', 'B', 'C'], from: D('2026-01-01'), to: null });
    expect(brief(segs)).toEqual(['2026-01-01→2026-04-30 2500.00 0', '2026-05-01→null 2900.00 1']);
  });

  it('has no figure while a unit has none, and the rule’s own amount is billed then', () => {
    const h = [row('A', '1000', '2026-03-01')];
    const segs = followSegments({ history: h, chargeTypeId: 'MGMT', unitIds: ['A'], from: D('2026-01-01'), to: null });
    expect(brief(segs)).toEqual(['2026-01-01→2026-02-28 - 0', '2026-03-01→null 1000.00 1']);
  });

  it('ignores a figure recorded at what is already billed, and other charges', () => {
    const h = [row(null, '2400', '2025-01-01'), row(null, '2400', '2026-06-01'), row(null, '999', '2026-03-01', 'RATES')];
    const segs = followSegments({ history: h, chargeTypeId: 'MGMT', unitIds: ['A'], from: D('2026-01-01'), to: null });
    expect(brief(segs)).toEqual(['2026-01-01→null 2400.00 0']);
  });

  it('tells a change on its first billing period only', () => {
    const segs = followSegments({
      history: property, chargeTypeId: 'MGMT', unitIds: ['A'], from: D('2026-01-01'), to: null,
      nextPeriod: (d) => nextPeriodStart(D('2026-01-01'), 1, new Date(d.getTime() + 86_400_000)),
    });
    expect(brief(segs)).toEqual(['2026-01-01→2026-11-30 2400.00 0', '2026-12-01→2026-12-31 2640.00 1', '2027-01-01→null 2640.00 0']);
  });

  it('keeps inside the rule’s own window', () => {
    const segs = followSegments({ history: property, chargeTypeId: 'MGMT', unitIds: ['A'], from: D('2026-01-01'), to: D('2026-10-31') });
    expect(brief(segs)).toEqual(['2026-01-01→2026-10-31 2400.00 0']);
  });

  it('names only the figures the units are billed at after the change', () => {
    // B's own figure takes effect the same day the property's does; only B's
    // reaches B, only the property's reaches A.
    const h = [row(null, '1000', '2025-01-01'), row(null, '1200', '2026-07-01'), row('B', '1800', '2026-07-01')];
    const segs = followSegments({ history: h, chargeTypeId: 'MGMT', unitIds: ['B'], from: D('2026-01-01'), to: null });
    expect(segs[1].changed).toEqual([h[2].id]);
  });
});

describe('followedFigureOn', () => {
  it('adds up the units that have a figure, and is null only when none has one', () => {
    const h = [row(null, '1000', '2025-01-01'), row('B', '1500', '2025-01-01')];
    expect(followedFigureOn(h, 'MGMT', ['A', 'B'], D('2026-01-01'))).toBe('2500.00');
    expect(followedFigureOn([row('B', '1500', '2025-01-01')], 'MGMT', ['A', 'B'], D('2026-01-01'))).toBe('1500.00');
    expect(followedFigureOn([], 'MGMT', ['A', 'B'], D('2026-01-01'))).toBeNull();
    expect(followedFigureOn(h, 'MGMT', [null], D('2026-01-01'))).toBe('1000.00');
  });
  it('resolves each unit against its own purchase’s figures when the lease spans two', () => {
    // A and B were bought in one purchase, C in another: one purchase's own
    // figure must not stand in for a unit of the other.
    const first = [row(null, '1000', '2025-01-01'), row('B', '1500', '2025-01-01')];
    const second = [row(null, '800', '2025-01-01')];
    const of = (unitId: string | null) => (unitId === 'C' ? second : first);
    expect(followedFigureOn(of, 'MGMT', ['A', 'B', 'C'], D('2026-01-01'))).toBe('3300.00');
    expect(followedFigureOn(of, 'MGMT', ['C'], D('2026-01-01'))).toBe('800.00');
  });
});

describe('followSegments across purchases', () => {
  it('changes where either purchase’s figure changes, each unit at its own', () => {
    const first = [row(null, '1000', '2025-01-01')];
    const second = [row(null, '800', '2025-01-01'), row(null, '900', '2026-07-01')];
    const of = (unitId: string | null) => (unitId === 'C' ? second : first);
    const segs = followSegments({ history: of, chargeTypeId: 'MGMT', unitIds: ['A', 'C'], from: D('2026-01-01'), to: null });
    expect(brief(segs)).toEqual(['2026-01-01→2026-06-30 1800.00 0', '2026-07-01→null 1900.00 1']);
  });
});
