import { describe, expect, it } from 'vitest';
import {
  allInForceOn,
  classifyPair,
  dayBefore,
  inForceOn,
  isInForce,
  opensAnOccurrence,
  ruleInForceOn,
  type LeaseRuleRow,
  type StandardChargeRow,
} from './standard-charge.resolution';

const D = (iso: string): Date => new Date(`${iso}T00:00:00.000Z`);

let seq = 0;
function row(partial: Partial<StandardChargeRow> & Pick<StandardChargeRow, 'amount' | 'effectiveFrom'>): StandardChargeRow {
  seq += 1;
  return {
    id: `sc${seq}`,
    unitId: null,
    chargeTypeId: 'MGMT',
    // Recorded in the order they are written unless a test says otherwise: only
    // a tie on effectiveFrom ever looks at this.
    createdAt: new Date(Date.UTC(2020, 0, 1, 0, 0, seq)),
    ...partial,
  };
}

function rule(partial: Partial<LeaseRuleRow> & Pick<LeaseRuleRow, 'amount'>): LeaseRuleRow {
  seq += 1;
  return {
    id: `cr${seq}`,
    chargeTypeId: 'MGMT',
    unitId: null,
    startDate: null,
    endDate: null,
    sortOrder: 0,
    ...partial,
  };
}

describe('standard charges — in force on a date', () => {
  it('picks the greatest effectiveFrom that has already started', () => {
    const history = [
      row({ id: 'old', amount: '500.00', effectiveFrom: D('2025-01-01') }),
      row({ id: 'mid', amount: '600.00', effectiveFrom: D('2026-04-01') }),
      row({ id: 'future', amount: '700.00', effectiveFrom: D('2026-09-01') }),
    ];
    expect(inForceOn(history, 'MGMT', null, D('2026-03-31'))?.row.id).toBe('old');
    expect(inForceOn(history, 'MGMT', null, D('2026-04-01'))?.row.id).toBe('mid');
    expect(inForceOn(history, 'MGMT', null, D('2026-08-31'))?.row.id).toBe('mid');
    expect(inForceOn(history, 'MGMT', null, D('2026-09-01'))?.row.id).toBe('future');
  });

  it('answers nothing before the first figure was ever recorded', () => {
    const history = [row({ amount: '500.00', effectiveFrom: D('2026-01-01') })];
    expect(inForceOn(history, 'MGMT', null, D('2025-12-31'))).toBeNull();
  });

  it('keeps each charge type on its own history', () => {
    const history = [
      row({ id: 'mgmt', chargeTypeId: 'MGMT', amount: '500.00', effectiveFrom: D('2026-01-01') }),
      row({ id: 'rates', chargeTypeId: 'RATES', amount: '900.00', effectiveFrom: D('2026-06-01') }),
    ];
    expect(inForceOn(history, 'MGMT', null, D('2026-07-01'))?.row.amount).toBe('500.00');
    expect(inForceOn(history, 'RATES', null, D('2026-07-01'))?.row.amount).toBe('900.00');
    expect(inForceOn(history, 'GOV_RENT', null, D('2026-07-01'))).toBeNull();
  });

  it('gives a unit the property figure when it has none of its own', () => {
    const history = [row({ id: 'prop', amount: '500.00', effectiveFrom: D('2026-01-01') })];
    const hit = inForceOn(history, 'MGMT', 'U1', D('2026-07-01'));
    expect(hit?.row.id).toBe('prop');
    expect(hit?.scope).toBe('PROPERTY');
  });

  it('lets a unit beat the property even when the property figure is NEWER', () => {
    // The case the office keeps a per-unit figure for: one shop negotiated its
    // own fee years ago, the building-wide notice must not overwrite it.
    const history = [
      row({ id: 'unit', unitId: 'U1', amount: '450.00', effectiveFrom: D('2024-01-01') }),
      row({ id: 'prop', amount: '600.00', effectiveFrom: D('2026-04-01') }),
    ];
    const hit = inForceOn(history, 'MGMT', 'U1', D('2026-07-01'));
    expect(hit?.row.id).toBe('unit');
    expect(hit?.scope).toBe('UNIT');
    // …while the unit next door, which has no figure, follows the building.
    expect(inForceOn(history, 'MGMT', 'U2', D('2026-07-01'))?.row.id).toBe('prop');
  });

  it('falls back to the property while the unit figure has not started yet', () => {
    const history = [
      row({ id: 'prop', amount: '500.00', effectiveFrom: D('2026-01-01') }),
      row({ id: 'unit', unitId: 'U1', amount: '450.00', effectiveFrom: D('2026-08-01') }),
    ];
    expect(inForceOn(history, 'MGMT', 'U1', D('2026-07-31'))?.row.id).toBe('prop');
    expect(inForceOn(history, 'MGMT', 'U1', D('2026-08-01'))?.row.id).toBe('unit');
  });

  it("does not let one unit's figure answer for another", () => {
    const history = [row({ id: 'u1', unitId: 'U1', amount: '450.00', effectiveFrom: D('2026-01-01') })];
    expect(inForceOn(history, 'MGMT', 'U2', D('2026-07-01'))).toBeNull();
  });

  it('breaks a same-day tie by what was recorded last, deterministically', () => {
    const a = row({ id: 'a', amount: '500.00', effectiveFrom: D('2026-04-01'), createdAt: D('2026-03-01') });
    const b = row({ id: 'b', amount: '600.00', effectiveFrom: D('2026-04-01'), createdAt: D('2026-03-02') });
    expect(inForceOn([a, b], 'MGMT', null, D('2026-05-01'))?.row.id).toBe('b');
    expect(inForceOn([b, a], 'MGMT', null, D('2026-05-01'))?.row.id).toBe('b');
  });

  it('marks exactly one row per scope as in force', () => {
    const history = [
      row({ id: 'old', amount: '500.00', effectiveFrom: D('2025-01-01') }),
      row({ id: 'now', amount: '600.00', effectiveFrom: D('2026-04-01') }),
      row({ id: 'later', amount: '700.00', effectiveFrom: D('2026-09-01') }),
      row({ id: 'unit', unitId: 'U1', amount: '450.00', effectiveFrom: D('2026-04-01') }),
    ];
    const on = D('2026-07-01');
    expect(history.filter((r) => isInForce(history, r, on)).map((r) => r.id)).toEqual(['now', 'unit']);
  });

  it('answers every charge type at once for one scope', () => {
    const history = [
      row({ id: 'm1', chargeTypeId: 'MGMT', amount: '500.00', effectiveFrom: D('2025-01-01') }),
      row({ id: 'm2', chargeTypeId: 'MGMT', amount: '600.00', effectiveFrom: D('2026-04-01') }),
      row({ id: 'r1', chargeTypeId: 'RATES', amount: '900.00', effectiveFrom: D('2026-01-01') }),
      row({ id: 'g1', chargeTypeId: 'GOV_RENT', amount: '100.00', effectiveFrom: D('2027-01-01') }),
    ];
    const all = allInForceOn(history, null, D('2026-07-01'));
    expect([...all.keys()].sort()).toEqual(['MGMT', 'RATES']);
    expect(all.get('MGMT')?.row.amount).toBe('600.00');
  });
});

describe('standard charges — the lease rule in force', () => {
  it('ignores a rule whose window has already closed', () => {
    const rules = [
      rule({ id: 'step1', amount: '500.00', endDate: D('2026-03-31') }),
      rule({ id: 'step2', amount: '600.00', startDate: D('2026-04-01') }),
    ];
    expect(ruleInForceOn(rules, 'MGMT', null, D('2026-03-31'))?.id).toBe('step1');
    expect(ruleInForceOn(rules, 'MGMT', null, D('2026-04-01'))?.id).toBe('step2');
  });

  it('prefers the rule bound to the unit over the whole-lease one', () => {
    const rules = [
      rule({ id: 'lease-wide', amount: '500.00' }),
      rule({ id: 'unit', unitId: 'U1', amount: '450.00' }),
    ];
    expect(ruleInForceOn(rules, 'MGMT', 'U1', D('2026-07-01'))?.id).toBe('unit');
    expect(ruleInForceOn(rules, 'MGMT', 'U2', D('2026-07-01'))?.id).toBe('lease-wide');
    expect(ruleInForceOn(rules, 'MGMT', null, D('2026-07-01'))?.id).toBe('lease-wide');
  });
});

describe('standard charges — what a new figure means for a tenancy', () => {
  const at = D('2026-04-01');

  it('offers a lease that charges a different amount', () => {
    const out = classifyPair([rule({ amount: '500.00' })], 'MGMT', null, at, '600.00');
    expect(out.kind).toBe('AFFECTED');
    expect(out.kind === 'AFFECTED' && out.rule.amount).toBe('500.00');
  });

  it('skips a lease already at the new amount', () => {
    expect(classifyPair([rule({ amount: '600.00' })], 'MGMT', null, at, '600.00').kind).toBe('ALREADY_AT_NEW_AMOUNT');
  });

  it('compares as money, not as text — 600 and 600.00 are the same amount', () => {
    expect(classifyPair([rule({ amount: '600' })], 'MGMT', null, at, '600.00').kind).toBe('ALREADY_AT_NEW_AMOUNT');
  });

  it('skips a lease that does not charge it at all', () => {
    const rules = [rule({ chargeTypeId: 'RENT', amount: '31000.00' })];
    expect(classifyPair(rules, 'MGMT', null, at, '600.00').kind).toBe('NOT_CHARGED_ON_THIS_LEASE');
  });

  it('skips a lease whose rule for it has already been closed off', () => {
    const rules = [rule({ amount: '500.00', endDate: D('2026-03-31') })];
    expect(classifyPair(rules, 'MGMT', null, at, '600.00').kind).toBe('NOT_CHARGED_ON_THIS_LEASE');
  });

  it('reads the amount from the step in force on the effective date', () => {
    const rules = [
      rule({ id: 'step1', amount: '500.00', endDate: D('2026-03-31') }),
      rule({ id: 'step2', amount: '550.00', startDate: D('2026-04-01') }),
    ];
    const out = classifyPair(rules, 'MGMT', null, at, '600.00');
    expect(out.kind === 'AFFECTED' && out.rule.id).toBe('step2');
  });

  it('applying twice is a no-op: the new rule is then the one in force', () => {
    // Exactly what the lease looks like after apply — the old rule closed on the
    // 31st, its successor from the 1st at the new amount.
    const applied = [
      rule({ id: 'closed', amount: '500.00', endDate: D('2026-03-31') }),
      rule({ id: 'new', amount: '600.00', startDate: D('2026-04-01') }),
    ];
    expect(classifyPair(applied, 'MGMT', null, at, '600.00').kind).toBe('ALREADY_AT_NEW_AMOUNT');
  });

  it('only looks at the unit the figure is for', () => {
    const rules = [
      rule({ id: 'u1', unitId: 'U1', amount: '450.00' }),
      rule({ id: 'u2', unitId: 'U2', amount: '500.00' }),
    ];
    expect(classifyPair(rules, 'MGMT', 'U1', at, '450.00').kind).toBe('ALREADY_AT_NEW_AMOUNT');
    expect(classifyPair(rules, 'MGMT', 'U2', at, '450.00').kind).toBe('AFFECTED');
  });
});

describe('standard charges — where the old rule is closed', () => {
  it('closes it the day before, leaving no gap and no overlap', () => {
    expect(dayBefore(D('2026-04-01')).toISOString().slice(0, 10)).toBe('2026-03-31');
    expect(dayBefore(D('2026-03-01')).toISOString().slice(0, 10)).toBe('2026-02-28');
    expect(dayBefore(D('2028-03-01')).toISOString().slice(0, 10)).toBe('2028-02-29'); // leap year
    expect(dayBefore(D('2026-01-01')).toISOString().slice(0, 10)).toBe('2025-12-31');
  });
});

describe('standard charges — where a whole-month charge may be stepped', () => {
  // The engine bills an N-monthly rule in the periods where
  // monthsSinceStart(lease.startDate, period) % N === 0, and charges a
  // FULL_MONTH rule the whole occurrence however few days it covers. A step
  // anywhere inside an occurrence therefore bills that occurrence twice.
  const start = D('2026-01-01');

  it('every 1st opens an occurrence for a monthly charge', () => {
    expect(opensAnOccurrence(start, D('2026-11-01'), 1)).toBe(true);
    expect(opensAnOccurrence(start, D('2026-11-15'), 1)).toBe(false);
  });

  it('a quarterly charge only opens one every third month from the lease start', () => {
    expect(opensAnOccurrence(start, D('2026-10-01'), 3)).toBe(true); // 9 % 3
    expect(opensAnOccurrence(start, D('2027-01-01'), 3)).toBe(true); // 12 % 3
    // The 1st of a month, but the SECOND month of the Oct–Dec quarter: stepping
    // here makes the closed rule and its successor each take a whole quarter.
    expect(opensAnOccurrence(start, D('2026-11-01'), 3)).toBe(false);
    expect(opensAnOccurrence(start, D('2026-12-01'), 3)).toBe(false);
  });

  it('is anchored on the lease start, not the calendar quarter', () => {
    const feb = D('2026-02-01');
    expect(opensAnOccurrence(feb, D('2026-11-01'), 3)).toBe(true); // 9 % 3
    expect(opensAnOccurrence(feb, D('2026-10-01'), 3)).toBe(false); // 8 % 3
  });

  it('a yearly charge opens one on the anniversary month only', () => {
    expect(opensAnOccurrence(start, D('2027-01-01'), 12)).toBe(true);
    expect(opensAnOccurrence(start, D('2026-07-01'), 12)).toBe(false);
  });

  it('a date before the lease starts opens nothing', () => {
    expect(opensAnOccurrence(start, D('2025-10-01'), 3)).toBe(false);
  });
});
