import { describe, expect, it } from 'vitest';
import { EngineChargeRule, expandChargeRules, LineSpec } from './billing.engine';

const lease = { startDate: new Date('2026-01-01'), endDate: new Date('2027-12-31') };

function rule(partial: Partial<EngineChargeRule> & Pick<EngineChargeRule, 'chargeTypeId' | 'amount'>): EngineChargeRule {
  return {
    label: partial.chargeTypeId,
    frequencyMonths: 1,
    timing: 'ADVANCE',
    proration: 'DAILY',
    firstInvoiceOnly: false,
    waivedDuringRentFree: false,
    startDate: null,
    endDate: null,
    sortOrder: 0,
    ...partial,
  };
}

const byType = (lines: LineSpec[], id: string) => lines.find((l) => l.chargeTypeId === id);

describe('billing engine — expandChargeRules', () => {
  it('bills a full month at the full amount', () => {
    const lines = expandChargeRules({
      lease,
      rules: [rule({ chargeTypeId: 'RENT', amount: '18000' })],
      period: '2026-06', // 30 days, fully within the lease
      isFirstInvoice: false,
    });
    expect(byType(lines, 'RENT')?.amount).toBe('18000.00');
  });

  it('pro-rates a partial first month by actual days (half-up)', () => {
    const midStart = { startDate: new Date('2026-01-15'), endDate: new Date('2027-12-31') };
    const lines = expandChargeRules({
      lease: midStart,
      rules: [rule({ chargeTypeId: 'RENT', amount: '18000' })],
      period: '2026-01', // Jan 15–31 = 17 of 31 days → 18000*17/31 = 9870.9677… → 9870.97
      isFirstInvoice: true,
    });
    expect(byType(lines, 'RENT')?.amount).toBe('9870.97');
  });

  it('charges FULL_MONTH even when the lease starts mid-month', () => {
    const midStart = { startDate: new Date('2026-01-15'), endDate: new Date('2027-12-31') };
    const lines = expandChargeRules({
      lease: midStart,
      rules: [rule({ chargeTypeId: 'MGMT', amount: '1200', proration: 'FULL_MONTH' })],
      period: '2026-01',
      isFirstInvoice: true,
    });
    expect(byType(lines, 'MGMT')?.amount).toBe('1200.00');
  });

  it('includes first-invoice-only deposits only on the first invoice', () => {
    const depositRule = rule({
      chargeTypeId: 'DEPOSIT',
      amount: '36000',
      proration: 'FULL_MONTH',
      firstInvoiceOnly: true,
      frequencyMonths: 0,
    });
    const first = expandChargeRules({ lease, rules: [depositRule], period: '2026-01', isFirstInvoice: true });
    const later = expandChargeRules({ lease, rules: [depositRule], period: '2026-02', isFirstInvoice: false });
    expect(byType(first, 'DEPOSIT')?.amount).toBe('36000.00');
    expect(byType(later, 'DEPOSIT')).toBeUndefined();
  });

  it('applies a quarterly charge only on aligned months', () => {
    const q = rule({ chargeTypeId: 'RATES', amount: '3000', frequencyMonths: 3, proration: 'FULL_MONTH' });
    // lease starts 2026-01 → months since: Jan=0, Apr=3, May=4
    const apr = expandChargeRules({ lease, rules: [q], period: '2026-04', isFirstInvoice: false });
    const may = expandChargeRules({ lease, rules: [q], period: '2026-05', isFirstInvoice: false });
    expect(byType(apr, 'RATES')?.amount).toBe('3000.00');
    expect(byType(may, 'RATES')).toBeUndefined();
  });

  it('excludes a charge whose own date window does not reach the period', () => {
    const ending = rule({ chargeTypeId: 'PROMO', amount: '500', endDate: new Date('2026-03-31') });
    const lines = expandChargeRules({ lease, rules: [ending], period: '2026-04', isFirstInvoice: false });
    expect(byType(lines, 'PROMO')).toBeUndefined();
  });

  it('excludes periods before the lease starts', () => {
    const late = { startDate: new Date('2026-06-01'), endDate: new Date('2027-12-31') };
    const lines = expandChargeRules({
      lease: late,
      rules: [rule({ chargeTypeId: 'RENT', amount: '18000' })],
      period: '2026-05',
      isFirstInvoice: false,
    });
    expect(byType(lines, 'RENT')).toBeUndefined();
  });

  it('pro-rates the final partial month when the lease ends mid-month', () => {
    const ending = { startDate: new Date('2026-01-01'), endDate: new Date('2026-04-10') };
    const lines = expandChargeRules({
      lease: ending,
      rules: [rule({ chargeTypeId: 'RENT', amount: '18000' })],
      period: '2026-04', // Apr 1–10 = 10 of 30 → 18000*10/30 = 6000.00
      isFirstInvoice: false,
    });
    expect(byType(lines, 'RENT')?.amount).toBe('6000.00');
  });

  it('bills a full multi-month charge at its full amount', () => {
    // quarterly rates, lease covers the whole Oct–Dec quarter
    const q = rule({ chargeTypeId: 'RATES', amount: '30000', frequencyMonths: 3, proration: 'DAILY' });
    const lines = expandChargeRules({ lease, rules: [q], period: '2026-10', isFirstInvoice: false });
    expect(byType(lines, 'RATES')?.amount).toBe('30000.00');
  });

  it('pro-rates a multi-month charge over the FULL window, not one month', () => {
    // lease starts mid-quarter: Oct 15 – Dec 31 = 78 of 92 days → 30000*78/92 = 25434.78
    const midQuarter = { startDate: new Date('2026-10-15'), endDate: new Date('2028-12-31') };
    const q = rule({ chargeTypeId: 'RATES', amount: '30000', frequencyMonths: 3, proration: 'DAILY' });
    const lines = expandChargeRules({ lease: midQuarter, rules: [q], period: '2026-10', isFirstInvoice: true });
    expect(byType(lines, 'RATES')?.amount).toBe('25434.78');
  });

  it('emits lines sorted by rule sortOrder', () => {
    const lines = expandChargeRules({
      lease,
      rules: [
        rule({ chargeTypeId: 'B', amount: '100', sortOrder: 2, proration: 'FULL_MONTH' }),
        rule({ chargeTypeId: 'A', amount: '100', sortOrder: 1, proration: 'FULL_MONTH' }),
      ],
      period: '2026-06',
      isFirstInvoice: false,
    });
    expect(lines.map((l) => l.chargeTypeId)).toEqual(['A', 'B']);
  });
});

/**
 * Rent-free periods. A Hong Kong tenancy often starts with a fit-out window or
 * free months at signing; the lease carries ONE such window, and WHICH charges
 * it frees is the charge type's `waivedDuringRentFree` flag — rent only, by the
 * owner's rule, with management fee and rates still payable.
 *
 * The arithmetic under test: the days of the occurrence the window covers are
 * taken off at the occurrence's own daily rate (amount ÷ the window's total
 * days), for FULL_MONTH exactly as for DAILY — half a free month is neither
 * free nor full.
 */
describe('billing engine — rent-free period', () => {
  const rentFree = (from: string, to: string, term = lease) => ({
    ...term,
    rentFreeFrom: new Date(from),
    rentFreeTo: new Date(to),
  });
  const rent = (partial: Partial<EngineChargeRule> = {}) =>
    rule({ chargeTypeId: 'RENT', amount: '18000', waivedDuringRentFree: true, ...partial });

  it('emits NO line at all when the whole period is rent-free', () => {
    const lines = expandChargeRules({
      lease: rentFree('2026-01-01', '2026-03-31'),
      rules: [rent()],
      period: '2026-02',
      isFirstInvoice: false,
    });
    // Not a 0.00 line: a debit note reading "Rent 0.00" looks like a mistake.
    expect(lines).toHaveLength(0);
  });

  it('charges the remaining days when the window covers the first half of a month', () => {
    const lines = expandChargeRules({
      lease: rentFree('2026-07-01', '2026-07-15'),
      rules: [rent()],
      period: '2026-07', // 31 days, 15 free → 16 × 18000/31 = 9290.3225… → 9290.32
      isFirstInvoice: false,
    });
    expect(byType(lines, 'RENT')?.amount).toBe('9290.32');
  });

  it('charges all but one day when the window covers the last day only', () => {
    const lines = expandChargeRules({
      lease: rentFree('2026-07-31', '2026-07-31'),
      rules: [rent()],
      period: '2026-07', // 30 of 31 days → 17419.3548… → 17419.35
      isFirstInvoice: false,
    });
    const line = byType(lines, 'RENT');
    expect(line?.amount).toBe('17419.35');
    // The line still covers the whole month — only the money is short.
    expect(line?.periodStart.toISOString().slice(0, 10)).toBe('2026-07-01');
    expect(line?.periodEnd.toISOString().slice(0, 10)).toBe('2026-07-31');
  });

  it('leaves a period the window does not reach completely alone', () => {
    const lines = expandChargeRules({
      lease: rentFree('2026-01-01', '2026-01-31'),
      rules: [rent()],
      period: '2026-06',
      isFirstInvoice: false,
    });
    expect(byType(lines, 'RENT')?.amount).toBe('18000.00');
    expect(byType(lines, 'RENT')?.meta).toBeUndefined();
  });

  it('leaves every charge alone when the lease has no window', () => {
    const lines = expandChargeRules({ lease, rules: [rent()], period: '2026-06', isFirstInvoice: false });
    expect(byType(lines, 'RENT')?.amount).toBe('18000.00');
  });

  it('prorates a quarterly charge over the WHOLE quarter, not one month', () => {
    // Quarterly rates, Jan–Mar 2026 = 90 days; free Jan 1 – Feb 15 = 46 days.
    // 44 × 30000/90 = 14666.666… → 14666.67. Dividing by one month would be
    // the classic divisor bug: it would bill more than the whole quarter.
    const q = rent({ chargeTypeId: 'RATES', amount: '30000', frequencyMonths: 3 });
    const lines = expandChargeRules({
      lease: rentFree('2026-01-01', '2026-02-15'),
      rules: [q],
      period: '2026-01',
      isFirstInvoice: true,
    });
    expect(byType(lines, 'RATES')?.amount).toBe('14666.67');
  });

  it('takes the free days off a FULL_MONTH charge too — days win over months', () => {
    const lines = expandChargeRules({
      lease: rentFree('2026-06-01', '2026-06-10'),
      rules: [rent({ proration: 'FULL_MONTH' })],
      period: '2026-06', // 10 of 30 days free → 20 × 18000/30 = 12000.00
      isFirstInvoice: false,
    });
    expect(byType(lines, 'RENT')?.amount).toBe('12000.00');
  });

  it('waives a FULL_MONTH charge at the month’s daily rate, not the covered days’', () => {
    // Lease starts mid-month, so FULL_MONTH would charge all 18000 for 15 days
    // of occupation. Five of those days are free → 18000 − 5 × 18000/30.
    // Dividing by the 15 covered days instead would hand back a third of the
    // month for five free days.
    const midStart = { startDate: new Date('2026-06-16'), endDate: new Date('2027-12-31') };
    const lines = expandChargeRules({
      lease: rentFree('2026-06-01', '2026-06-20', midStart),
      rules: [rent({ proration: 'FULL_MONTH' })],
      period: '2026-06',
      isFirstInvoice: true,
    });
    expect(byType(lines, 'RENT')?.amount).toBe('15000.00');
  });

  it('waives only the flagged charge type — management fee and rates still bill', () => {
    const lines = expandChargeRules({
      lease: rentFree('2026-06-01', '2026-06-15'),
      rules: [
        rent({ sortOrder: 0 }),
        rule({ chargeTypeId: 'MGMT', amount: '1200', proration: 'FULL_MONTH', sortOrder: 1 }),
        rule({ chargeTypeId: 'RATES', amount: '800', sortOrder: 2 }),
      ],
      period: '2026-06', // 15 of 30 days free
      isFirstInvoice: false,
    });
    expect(byType(lines, 'RENT')?.amount).toBe('9000.00');
    expect(byType(lines, 'MGMT')?.amount).toBe('1200.00');
    expect(byType(lines, 'RATES')?.amount).toBe('800.00');
    expect(byType(lines, 'MGMT')?.meta).toBeUndefined();
    expect(byType(lines, 'RATES')?.meta).toBeUndefined();
  });

  it('never waives a deposit or other first-invoice-only charge', () => {
    // Even if someone flags the deposit's charge type: signing money is not rent
    // for a period, so a fit-out window cannot touch it.
    const deposit = rent({ chargeTypeId: 'DEPOSIT', amount: '36000', proration: 'FULL_MONTH', firstInvoiceOnly: true, frequencyMonths: 0 });
    const lines = expandChargeRules({
      lease: rentFree('2026-01-01', '2026-01-31'),
      rules: [deposit],
      period: '2026-01',
      isFirstInvoice: true,
    });
    expect(byType(lines, 'DEPOSIT')?.amount).toBe('36000.00');
    expect(byType(lines, 'DEPOSIT')?.meta).toBeUndefined();
  });

  it('clips a window that starts before the lease does', () => {
    const lateStart = { startDate: new Date('2026-01-10'), endDate: new Date('2027-12-31') };
    const lines = expandChargeRules({
      lease: rentFree('2025-12-01', '2026-01-20', lateStart),
      rules: [rent()],
      period: '2026-01', // covered Jan 10–31 (22d); free Jan 10–20 (11d) → 11 × 18000/31
      isFirstInvoice: true,
    });
    const line = byType(lines, 'RENT');
    expect(line?.amount).toBe('6387.10');
    expect(line?.meta?.rentFree).toEqual({ from: '2026-01-10', to: '2026-01-20', days: 11, billedDays: 11, totalDays: 31 });
  });

  it('clips a window that runs past the end of the lease', () => {
    const earlyEnd = { startDate: new Date('2026-01-01'), endDate: new Date('2026-04-10') };
    const lines = expandChargeRules({
      lease: rentFree('2026-04-05', '2026-05-31', earlyEnd),
      rules: [rent()],
      period: '2026-04', // covered Apr 1–10 (10d); free Apr 5–10 (6d) → 4 × 18000/30
      isFirstInvoice: false,
    });
    const line = byType(lines, 'RENT');
    expect(line?.amount).toBe('2400.00');
    expect(line?.meta?.rentFree).toEqual({ from: '2026-04-05', to: '2026-04-10', days: 6, billedDays: 4, totalDays: 30 });
  });

  it('emits no line when every covered day of a part-month is free', () => {
    const earlyEnd = { startDate: new Date('2026-01-01'), endDate: new Date('2026-04-10') };
    const lines = expandChargeRules({
      lease: rentFree('2026-03-20', '2026-05-31', earlyEnd),
      rules: [rent()],
      period: '2026-04', // covered Apr 1–10, all of it free
      isFirstInvoice: false,
    });
    expect(lines).toHaveLength(0);
  });

  it('counts the real length of 28, 29, 30 and 31 day months', () => {
    // One free day in each, so the amount is a direct read-out of the divisor.
    const long = { startDate: new Date('2026-01-01'), endDate: new Date('2029-12-31') };
    const oneFreeDay = (day: string, period: string) =>
      byType(
        expandChargeRules({ lease: rentFree(day, day, long), rules: [rent()], period, isFirstInvoice: false }),
        'RENT',
      )?.amount;
    expect(oneFreeDay('2026-01-01', '2026-01')).toBe('17419.35'); // 30/31
    expect(oneFreeDay('2026-02-01', '2026-02')).toBe('17357.14'); // 27/28
    expect(oneFreeDay('2026-04-01', '2026-04')).toBe('17400.00'); // 29/30
    expect(oneFreeDay('2028-02-01', '2028-02')).toBe('17379.31'); // 28/29 — leap year
    expect(oneFreeDay('2028-02-29', '2028-02')).toBe('17379.31'); // the leap day itself
  });

  it('frees a whole leap February', () => {
    const long = { startDate: new Date('2026-01-01'), endDate: new Date('2029-12-31') };
    const lines = expandChargeRules({
      lease: rentFree('2028-02-01', '2028-02-29', long),
      rules: [rent()],
      period: '2028-02',
      isFirstInvoice: false,
    });
    expect(lines).toHaveLength(0);
  });

  it('says on the line which days were free, and carries them in meta', () => {
    const lines = expandChargeRules({
      lease: rentFree('2026-05-20', '2026-06-10'),
      rules: [rent()],
      period: '2026-06',
      isFirstInvoice: false,
    });
    const line = byType(lines, 'RENT');
    expect(line?.description).toBe('RENT · 2026-06 — rent-free 2026-06-01 → 2026-06-10 (10 day(s) not charged)');
    expect(line?.meta?.rentFree).toEqual({ from: '2026-06-01', to: '2026-06-10', days: 10, billedDays: 20, totalDays: 30 });
  });

  it('keeps the coverage window in the description when the month is also part-covered', () => {
    const midStart = { startDate: new Date('2026-06-16'), endDate: new Date('2027-12-31') };
    const lines = expandChargeRules({
      lease: rentFree('2026-06-16', '2026-06-20', midStart),
      rules: [rent()],
      period: '2026-06',
      isFirstInvoice: true,
    });
    expect(byType(lines, 'RENT')?.description).toBe(
      'RENT (2026-06-16 → 2026-06-30) — rent-free 2026-06-16 → 2026-06-20 (5 day(s) not charged)',
    );
    // Covered Jun 16–30 = 15 days, 5 free → 10 × 18000/30 = 6000.00
    expect(byType(lines, 'RENT')?.amount).toBe('6000.00');
  });
});
