/**
 * Functional smoke: standard charges — what a recurring charge costs at an
 * address, and what changing it does to the tenancies already running.
 *
 * The office's spreadsheet records a management fee and rates per property and
 * per unit, "subject to change with notice". The system only ever had those
 * amounts retyped into every lease, so nobody could answer "what was it in May"
 * and a building-wide increase meant opening every tenancy by hand.
 *
 * What this proves against the real service and the real billing engine:
 *   · a figure is recorded per property or per unit, with history — a change is
 *     a NEW row, and the old one still answers for the months it covered;
 *   · resolution: greatest effectiveFrom that has started, and a unit's own
 *     figure beats the property's even when the property's is newer;
 *   · a new lease is OFFERED those figures for its start date, as ordinary
 *     editable charge rules — one per unit;
 *   · the review after a change lists the right tenancies at the right amounts,
 *     and says why the others are left out;
 *   · applying steps the lease's charge rule — closed the day before, successor
 *     from the effective date — so three months straddling the change bill the
 *     old amount, then both parts of the split month to the cent, then the new
 *     amount: no gap, no double charge;
 *   · an ISSUED debit note's amounts are untouched by any of it, while a DRAFT
 *     picks the change up when it is rebuilt (and the apply result says which);
 *   · a whole-month charge refuses to step inside one of its billing periods
 *     rather than bill that period twice — measured in periods, so a quarterly
 *     one is refused on the 1st of a month that is not the start of its quarter;
 *   · a charge the tenancy bills for the WHOLE lease is reported, never stepped
 *     from a per-unit figure, and reported once however many units it covers;
 *   · a note whose period label is before the change but whose window covers it
 *     is listed for rebuild, and rebuilding splits it to the cent;
 *   · correcting or deleting a row changes what resolves, and never un-writes a
 *     charge rule already agreed on a lease;
 *   · org scoping and the permission each action actually needs.
 *
 * Standalone, self-cleaning: its own ZZ organisation, purged at both ends.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/standard-charge-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { ApprovalService } from '../src/approvals/approval.service';
import { BillingService } from '../src/billing/billing.service';
import { NumberService } from '../src/common/number.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { leasesRouter } from '../src/trpc/routers/leases.router';
import { standardChargesRouter } from '../src/trpc/routers/standard-charges.router';
import type { AuthUser } from '../src/trpc/auth-user';
import type { Context } from '../src/trpc/trpc';

const prisma = new PrismaService();
const billing = new BillingService(prisma, new LedgerService(), new NumberService(), new EventEmitter2(), new ApprovalService(prisma));

let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };
async function refused(fn: () => Promise<unknown>): Promise<string> {
  try { await fn(); return ''; } catch (e) { return e instanceof Error ? e.message : String(e); }
}

const PFX = 'ZZ-SC';
const ORG_CODE = `${PFX}-ORG`;
const OTHER_ORG_CODE = `${PFX}-ORG2`;
const FULL = [
  'property.read', 'property.update', 'lease.read', 'lease.create', 'lease.update',
  'charge-type.read', 'notice.read', 'notice.create',
];

function ctxFor(orgId: string, permissions: string[]): Context {
  const user: AuthUser = { id: 'zz-sc-staff', email: 'zz-sc@rms.local', name: 'ZZ SC', tenantId: null, mustChangePassword: false, roles: ['ADMIN'], permissions };
  return { prisma, user, organizationId: orgId } as unknown as Context;
}

/** Lines of a note by charge type code, so an assertion reads like the paper. */
async function linesOf(invoiceId: string) {
  const rows = await prisma.invoiceLine.findMany({
    where: { invoiceId },
    orderBy: { sortOrder: 'asc' },
    include: { chargeType: { select: { code: true } } },
  });
  return rows.map((l) => ({ code: l.chargeType?.code ?? null, description: l.description, amount: l.amount.toFixed(2) }));
}
const allOf = (lines: Awaited<ReturnType<typeof linesOf>>, code: string) => lines.filter((l) => l.code === code);
const sumOf = (lines: Awaited<ReturnType<typeof linesOf>>, code: string) =>
  allOf(lines, code).reduce((s, l) => s + Number(l.amount), 0).toFixed(2);
const d = (v: Date | null) => (v ? v.toISOString().slice(0, 10) : null);

async function purgeOrg(code: string) {
  const org = await prisma.organization.findUnique({ where: { code }, select: { id: true } });
  if (!org) return;
  const leases = await prisma.lease.findMany({ where: { organizationId: org.id }, select: { id: true } });
  const leaseIds = leases.map((l) => l.id);
  const invs = leaseIds.length ? await prisma.invoice.findMany({ where: { leaseId: { in: leaseIds } }, select: { id: true } }) : [];
  const invIds = invs.map((i) => i.id);
  await prisma.journalLine.deleteMany({ where: { entry: { organizationId: org.id } } });
  await prisma.journalEntry.deleteMany({ where: { organizationId: org.id } });
  if (invIds.length) {
    await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invIds } } });
    await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
  }
  await prisma.propertyNotice.deleteMany({ where: { organizationId: org.id } });
  await prisma.standardCharge.deleteMany({ where: { organizationId: org.id } });
  if (leaseIds.length) {
    await prisma.chargeRule.deleteMany({ where: { leaseId: { in: leaseIds } } });
    await prisma.leaseUnit.deleteMany({ where: { leaseId: { in: leaseIds } } });
    await prisma.lease.updateMany({ where: { id: { in: leaseIds } }, data: { renewedFromId: null } });
    await prisma.lease.deleteMany({ where: { id: { in: leaseIds } } });
  }
  const props = await prisma.property.findMany({ where: { organizationId: org.id }, select: { id: true } });
  await prisma.unit.deleteMany({ where: { propertyId: { in: props.map((p) => p.id) } } });
  await prisma.property.deleteMany({ where: { id: { in: props.map((p) => p.id) } } });
  await prisma.tenant.deleteMany({ where: { organizationId: org.id } });
  await prisma.chargeType.deleteMany({ where: { organizationId: org.id } });
  await prisma.glAccount.deleteMany({ where: { organizationId: org.id } });
  await prisma.numberSequence.deleteMany({ where: { organizationId: org.id } });
  await prisma.referenceValue.deleteMany({ where: { organizationId: org.id } });
  await prisma.organization.delete({ where: { id: org.id } });
}
const purge = async () => { await purgeOrg(ORG_CODE); await purgeOrg(OTHER_ORG_CODE); };

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'Standard charge smoke org' } })).id;
  const sc = standardChargesRouter.createCaller(ctxFor(orgId, FULL));
  const leases = leasesRouter.createCaller(ctxFor(orgId, FULL));

  const gl: Record<string, string> = {};
  for (const g of [
    { code: '1100', name: 'AR', type: 'ASSET' as const, role: 'RECEIVABLE' as const },
    { code: '4000', name: 'Rental Income', type: 'INCOME' as const },
    { code: '4100', name: 'Management Fee Income', type: 'INCOME' as const },
    { code: '2100', name: 'Rates Payable', type: 'LIABILITY' as const },
  ]) gl[g.code] = (await prisma.glAccount.create({ data: { organizationId: orgId, ...g } })).id;
  await prisma.numberSequence.create({ data: { organizationId: orgId, docType: 'INVOICE', prefix: 'ZZSC-', padding: 6 } });

  const mk = (code: string, nameEn: string, category: 'RECURRING' | 'DEPOSIT', glCode: string, sortOrder: number) =>
    prisma.chargeType.create({ data: { organizationId: orgId, code, nameEn, category, glAccountId: gl[glCode], sortOrder } });
  const rentCt = await mk('RENT', 'Rent', 'RECURRING', '4000', 0);
  const mgmtCt = await mk('MGMT_FEE', 'Management Fee', 'RECURRING', '4100', 1);
  const ratesCt = await mk('RATES', 'Government Rates', 'RECURRING', '2100', 2);
  const depositCt = await mk('RENT_DEPOSIT', 'Rent Deposit', 'DEPOSIT', '2100', 3);

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: `${PFX} Tenant` } });
  const prop = await prisma.property.create({
    data: { organizationId: orgId, name: `${PFX} Property`, units: { create: [{ name: 'U1' }, { name: 'U2' }, { name: 'U3' }, { name: 'U4' }, { name: 'U5' }] } },
  });
  const units = await prisma.unit.findMany({ where: { propertyId: prop.id }, orderBy: { name: 'asc' } });
  const U = Object.fromEntries(units.map((u) => [u.name, u.id])) as Record<string, string>;
  const other = await prisma.property.create({ data: { organizationId: orgId, name: `${PFX} Other Property`, units: { create: [{ name: 'X1' }] } } });
  const otherUnit = await prisma.unit.findFirstOrThrow({ where: { propertyId: other.id } });

  console.log('A. Figures are recorded per property and per unit, and kept as history');
  const mgmt500 = await sc.create({ propertyId: prop.id, chargeTypeId: mgmtCt.id, amount: '500', effectiveFrom: '2026-01-01', note: 'as per 2025 AGM' });
  const mgmt600 = await sc.create({ propertyId: prop.id, chargeTypeId: mgmtCt.id, amount: '600', effectiveFrom: '2026-07-01' });
  // Older than the property's, and must still win for its own unit.
  const u1Mgmt = await sc.create({ propertyId: prop.id, unitId: U.U1, chargeTypeId: mgmtCt.id, amount: '450', effectiveFrom: '2025-06-01' });
  const rates900 = await sc.create({ propertyId: prop.id, chargeTypeId: ratesCt.id, amount: '900', effectiveFrom: '2026-01-01' });
  const listed = await sc.list({ propertyId: prop.id, onDate: '2026-03-01' });
  ck('A1 all four rows are kept — a change never edits the old figure', listed.rows.length === 4, String(listed.rows.length));
  ck('A2 the amount and the note round-trip', listed.rows.find((r) => r.id === mgmt500.id)?.amount === '500.00'
    && listed.rows.find((r) => r.id === mgmt500.id)?.note === 'as per 2025 AGM');
  ck('A3 the July figure is marked as not yet due on 1 March',
    listed.rows.find((r) => r.id === mgmt600.id)?.future === true && listed.rows.find((r) => r.id === mgmt600.id)?.inForce === false);
  ck('A4 the January figure is the one in force on 1 March', listed.rows.find((r) => r.id === mgmt500.id)?.inForce === true);
  ck('A5 the picker offers recurring charge types only',
    listed.chargeTypes.every((c) => c.id !== depositCt.id) && listed.chargeTypes.some((c) => c.id === mgmtCt.id),
    JSON.stringify(listed.chargeTypes.map((c) => c.code)));

  console.log('\nB. Resolution: the latest figure that has started, unit beats property');
  const march = listed.effective;
  const eff = (rows: typeof march, unitId: string | null, chargeTypeId: string) => rows.find((e) => e.unitId === unitId && e.chargeTypeId === chargeTypeId);
  ck('B1 the property itself pays 500 in March', eff(march, null, mgmtCt.id)?.amount === '500.00', eff(march, null, mgmtCt.id)?.amount);
  ck('B2 U1 pays its own 450, from its own older row', eff(march, U.U1, mgmtCt.id)?.amount === '450.00' && eff(march, U.U1, mgmtCt.id)?.scope === 'UNIT');
  ck('B3 U2, which has no figure of its own, follows the building', eff(march, U.U2, mgmtCt.id)?.amount === '500.00' && eff(march, U.U2, mgmtCt.id)?.scope === 'PROPERTY');
  const august = (await sc.list({ propertyId: prop.id, onDate: '2026-08-01' })).effective;
  ck('B4 in August the building pays 600', eff(august, null, mgmtCt.id)?.amount === '600.00');
  ck('B5 …and so does U2', eff(august, U.U2, mgmtCt.id)?.amount === '600.00');
  ck('B6 …while U1 still pays its own 450 — the notice did not overwrite it', eff(august, U.U1, mgmtCt.id)?.amount === '450.00');
  const dec2025 = (await sc.list({ propertyId: prop.id, onDate: '2025-12-31' })).effective;
  ck('B7 before the first figure there is no answer for the building', eff(dec2025, null, mgmtCt.id) === undefined);
  ck('B8 …though U1 already had one', eff(dec2025, U.U1, mgmtCt.id)?.amount === '450.00');

  console.log('\nC. What a figure refuses to be');
  const dup = await refused(() => sc.create({ propertyId: prop.id, chargeTypeId: mgmtCt.id, amount: '650', effectiveFrom: '2026-07-01' }));
  ck('C1 a second figure for the same scope and date is refused', dup.includes('already starts on that date'), `got "${dup}"`);
  const dupUnit = await sc.create({ propertyId: prop.id, unitId: U.U2, chargeTypeId: mgmtCt.id, amount: '650', effectiveFrom: '2026-07-01' });
  ck('C2 …but the same date for a DIFFERENT scope is fine', Boolean(dupUnit.id));
  await sc.remove({ id: dupUnit.id });
  const notRecurring = await refused(() => sc.create({ propertyId: prop.id, chargeTypeId: depositCt.id, amount: '1000', effectiveFrom: '2026-01-01' }));
  ck('C3 a deposit has no standard monthly amount', notRecurring.includes('Only a recurring charge'), `got "${notRecurring}"`);
  const wrongUnit = await refused(() => sc.create({ propertyId: prop.id, unitId: otherUnit.id, chargeTypeId: mgmtCt.id, amount: '500', effectiveFrom: '2026-01-01' }));
  ck('C4 a unit from another building is refused', wrongUnit.includes('not on this property'), `got "${wrongUnit}"`);

  console.log('\nD. A new lease is OFFERED the figures for its start date');
  const pre = await leases.standardChargePrefill({ unitIds: [U.U1, U.U2], startDate: '2026-03-01' });
  const find = (rules: typeof pre.rules, unitId: string | null, chargeTypeId: string) => rules.find((r) => r.unitId === unitId && r.chargeTypeId === chargeTypeId);
  ck('D1 one rule per unit per charge type', pre.rules.length === 4, JSON.stringify(pre.rules.map((r) => `${r.unitName}:${r.chargeTypeCode}=${r.amount}`)));
  ck('D2 U1 is offered its own 450', find(pre.rules, U.U1, mgmtCt.id)?.amount === '450.00');
  ck('D3 U2 is offered the building’s 500', find(pre.rules, U.U2, mgmtCt.id)?.amount === '500.00');
  ck('D4 both are offered the rates', find(pre.rules, U.U1, ratesCt.id)?.amount === '900.00' && find(pre.rules, U.U2, ratesCt.id)?.amount === '900.00');
  ck('D5 in the shape a user would have typed — monthly, in advance, prorated daily',
    pre.rules.every((r) => r.frequencyMonths === 1 && r.timing === 'ADVANCE' && r.proration === 'DAILY' && r.firstInvoiceOnly === false));
  ck('D6 and it says where each amount came from',
    find(pre.rules, U.U1, mgmtCt.id)?.standardChargeId === u1Mgmt.id && find(pre.rules, U.U1, mgmtCt.id)?.scope === 'UNIT'
    && find(pre.rules, U.U2, mgmtCt.id)?.scope === 'PROPERTY');
  const preAug = await leases.standardChargePrefill({ unitIds: [U.U2], startDate: '2026-08-01' });
  ck('D7 a tenancy starting in August is offered 600', find(preAug.rules, U.U2, mgmtCt.id)?.amount === '600.00');
  const preNoUnits = await leases.standardChargePrefill({ unitIds: [], startDate: '2026-03-01' });
  // The figures are the units' properties' — a lease may take its units from
  // several purchases of a building — so naming none names nothing to offer.
  ck('D8 a lease naming no unit is offered nothing', preNoUnits.rules.length === 0);
  const preOther = await leases.standardChargePrefill({ unitIds: [otherUnit.id], startDate: '2026-03-01' });
  ck('D9 a building with no figures offers nothing', preOther.rules.length === 0);
  // Nothing is forced: the prefill wrote nothing.
  ck('D10 offering changed no data', (await prisma.chargeRule.count({ where: { lease: { organizationId: orgId } } })) === 0);

  console.log('\nE. The review after a change');
  const rules = (ruleSet: { chargeTypeId: string; amount: string; unitId?: string | null; proration?: 'DAILY' | 'FULL_MONTH'; frequencyMonths?: number }[]) =>
    ruleSet.map((r) => ({
      chargeTypeId: r.chargeTypeId, amount: r.amount, frequencyMonths: r.frequencyMonths ?? 1, timing: 'ADVANCE' as const,
      proration: r.proration ?? ('DAILY' as const), firstInvoiceOnly: false, unitId: r.unitId ?? null,
    }));
  const base = { tenantId: tenant.id, currency: 'HKD' as const, depositMonths: 0, startDate: '2026-01-01', endDate: '2027-12-31' };
  const l1 = await leases.create({ ...base, reference: `${PFX}-L1`, status: 'ACTIVE', unitIds: [U.U2], chargeRules: rules([{ chargeTypeId: rentCt.id, amount: '31000' }, { chargeTypeId: mgmtCt.id, amount: '500', unitId: U.U2 }, { chargeTypeId: ratesCt.id, amount: '900', unitId: U.U2 }]) });
  const l2 = await leases.create({ ...base, reference: `${PFX}-L2`, status: 'ACTIVE', unitIds: [U.U1], chargeRules: rules([{ chargeTypeId: mgmtCt.id, amount: '450', unitId: U.U1 }]) });
  const l3 = await leases.create({ ...base, reference: `${PFX}-L3`, status: 'DRAFT', unitIds: [U.U3], chargeRules: rules([{ chargeTypeId: mgmtCt.id, amount: '500', unitId: U.U3 }]) });
  const l4 = await leases.create({ ...base, reference: `${PFX}-L4`, status: 'ACTIVE', endDate: '2026-05-31', unitIds: [U.U3], chargeRules: rules([{ chargeTypeId: mgmtCt.id, amount: '500', unitId: U.U3 }]) });
  const l5 = await leases.create({ ...base, reference: `${PFX}-L5`, status: 'ACTIVE', unitIds: [U.U4], chargeRules: rules([{ chargeTypeId: rentCt.id, amount: '20000' }]) });
  const l6 = await leases.create({ ...base, reference: `${PFX}-L6`, status: 'ACTIVE', unitIds: [U.U5], chargeRules: rules([{ chargeTypeId: mgmtCt.id, amount: '600', unitId: U.U5 }]) });

  const review = await sc.affectedLeases({ id: mgmt600.id });
  const aff = (leaseId: string) => review.affected.find((a) => a.leaseId === leaseId);
  const skip = (leaseId: string) => review.skipped.find((s) => s.leaseId === leaseId);
  ck('E1 exactly one tenancy is offered', review.affected.length === 1, JSON.stringify(review.affected.map((a) => `${a.leaseReference}/${a.unitName}`)));
  ck('E2 it is L1 on U2, 500 → 600 from 2026-07-01',
    aff(l1.id)?.unitId === U.U2 && aff(l1.id)?.currentAmount === '500.00' && aff(l1.id)?.newAmount === '600.00' && aff(l1.id)?.effectiveFrom === '2026-07-01',
    JSON.stringify(aff(l1.id)));
  ck('E3 and it would be written as a step, unblocked', aff(l1.id)?.mode === 'STEPPED' && aff(l1.id)?.blockedReason === null);
  ck('E4 L2 is absent entirely — U1 has its own figure, which this notice does not touch', aff(l2.id) === undefined && skip(l2.id) === undefined);
  ck('E5 the DRAFT lease is not reviewed', aff(l3.id) === undefined && skip(l3.id) === undefined);
  ck('E6 a tenancy that ends before the change is not reviewed', aff(l4.id) === undefined && skip(l4.id) === undefined);
  ck('E7 a tenancy that does not charge a management fee is reported, not offered',
    skip(l5.id)?.reason === 'NOT_CHARGED_ON_THIS_LEASE' && skip(l5.id)?.currentAmount === null, JSON.stringify(skip(l5.id)));
  ck('E8 a tenancy already at 600 is reported as already matching',
    skip(l6.id)?.reason === 'ALREADY_AT_NEW_AMOUNT' && skip(l6.id)?.currentAmount === '600.00', JSON.stringify(skip(l6.id)));
  ck('E9 the review names the figure it is about', review.standardCharge.amount === '600.00' && review.standardCharge.chargeTypeCode === 'MGMT_FEE');
  ck('E10 reviewing changed nothing', (await prisma.chargeRule.count({ where: { leaseId: l1.id } })) === 3);

  console.log('\nF. A note raised BEFORE the change: issued is history, draft is rebuildable');
  const june = await billing.generateDraft({ organizationId: orgId, leaseId: l1.id, period: '2026-06' });
  const issued = await billing.issue({ organizationId: orgId, invoiceId: june.id });
  ck('F1 June is issued at the old management fee', sumOf(await linesOf(issued.id), 'MGMT_FEE') === '500.00');
  const julyDraft = await billing.generateDraft({ organizationId: orgId, leaseId: l1.id, period: '2026-07' });
  ck('F2 a July draft raised before the change also says 500', sumOf(await linesOf(julyDraft.id), 'MGMT_FEE') === '500.00');

  console.log('\nG. Applying the change to the ticked tenancy');
  const applied = await sc.applyToLeases({ id: mgmt600.id, targets: [{ leaseId: l1.id, unitId: U.U2 }] });
  ck('G1 one tenancy was stepped', applied.applied.length === 1 && applied.applied[0].mode === 'STEPPED', JSON.stringify(applied.applied));
  ck('G2 it reports what changed', applied.applied[0].previousAmount === '500.00' && applied.applied[0].newAmount === '600.00');
  ck('G3 and names the draft that has to be rebuilt to pick it up',
    applied.draftInvoices.length === 1 && applied.draftInvoices[0].id === julyDraft.id, JSON.stringify(applied.draftInvoices));
  ck('G4 the issued June note is NOT listed', !applied.draftInvoices.some((i) => i.id === issued.id));

  const mgmtRules = await prisma.chargeRule.findMany({ where: { leaseId: l1.id, chargeTypeId: mgmtCt.id }, orderBy: { amount: 'asc' } });
  ck('G5 exactly two management-fee rules now', mgmtRules.length === 2, JSON.stringify(mgmtRules.map((r) => `${r.amount}:${d(r.startDate)}→${d(r.endDate)}`)));
  const oldRule = mgmtRules.find((r) => r.amount.toFixed(2) === '500.00')!;
  const newRule = mgmtRules.find((r) => r.amount.toFixed(2) === '600.00')!;
  ck('G6 the old one is closed the day before the change', d(oldRule.endDate) === '2026-06-30', String(d(oldRule.endDate)));
  ck('G7 the new one starts on the change date — consecutive days, no gap, no overlap', d(newRule.startDate) === '2026-07-01', String(d(newRule.startDate)));
  ck('G8 the successor keeps the original’s unit, frequency, timing and proration',
    newRule.unitId === U.U2 && newRule.frequencyMonths === oldRule.frequencyMonths && newRule.timing === oldRule.timing && newRule.proration === oldRule.proration);
  ck('G9 the lease form can read both back with their windows',
    (await leases.get({ id: l1.id })).chargeRules.filter((r) => r.chargeTypeId === mgmtCt.id).length === 2);
  ck('G10 nothing else on the lease was touched', (await prisma.chargeRule.count({ where: { leaseId: l1.id } })) === 4);

  console.log('\nH. The issued note is untouched; the draft picks it up when rebuilt');
  ck('H1 the ISSUED June note still says 500.00', sumOf(await linesOf(issued.id), 'MGMT_FEE') === '500.00', sumOf(await linesOf(issued.id), 'MGMT_FEE'));
  const arLine = await prisma.journalLine.findMany({ where: { invoiceId: issued.id, accountId: gl['1100'] }, select: { amount: true } });
  ck('H2 and so does what it posted to the ledger', arLine.length === 1 && arLine[0].amount.toFixed(2) === '32400.00', JSON.stringify(arLine.map((l) => l.amount.toFixed(2))));
  ck('H3 the July draft still says 500 until it is rebuilt', sumOf(await linesOf(julyDraft.id), 'MGMT_FEE') === '500.00');
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: julyDraft.id });
  ck('H4 rebuilding it gives 600.00', sumOf(await linesOf(julyDraft.id), 'MGMT_FEE') === '600.00', sumOf(await linesOf(julyDraft.id), 'MGMT_FEE'));
  ck('H5 as ONE line, not two', allOf(await linesOf(julyDraft.id), 'MGMT_FEE').length === 1);

  console.log('\nI. Applying twice is a no-op, and a stale tick is refused');
  const reviewAgain = await sc.affectedLeases({ id: mgmt600.id });
  ck('I1 L1 is now reported as already matching', reviewAgain.affected.length === 0 && reviewAgain.skipped.find((s) => s.leaseId === l1.id)?.reason === 'ALREADY_AT_NEW_AMOUNT');
  const stale = await refused(() => sc.applyToLeases({ id: mgmt600.id, targets: [{ leaseId: l1.id, unitId: U.U2 }] }));
  ck('I2 ticking it again is refused rather than written twice', stale.includes('no longer affected'), `got "${stale}"`);
  ck('I3 still exactly two management-fee rules', (await prisma.chargeRule.count({ where: { leaseId: l1.id, chargeTypeId: mgmtCt.id } })) === 2);

  console.log('\nJ. A mid-month change, billed across three months to the cent');
  const rates1000 = await sc.create({ propertyId: prop.id, chargeTypeId: ratesCt.id, amount: '1000', effectiveFrom: '2026-09-15' });
  const ratesReview = await sc.affectedLeases({ id: rates1000.id });
  ck('J1 L1 is offered, 900 → 1000 from 2026-09-15',
    ratesReview.affected.length === 1 && ratesReview.affected[0].currentAmount === '900.00' && ratesReview.affected[0].blockedReason === null,
    JSON.stringify(ratesReview.affected));
  await sc.applyToLeases({ id: rates1000.id, targets: [{ leaseId: l1.id, unitId: U.U2 }] });
  const aug = await billing.generateDraft({ organizationId: orgId, leaseId: l1.id, period: '2026-08' });
  ck('J2 August, entirely before the change: 900.00 on one line',
    sumOf(await linesOf(aug.id), 'RATES') === '900.00' && allOf(await linesOf(aug.id), 'RATES').length === 1, sumOf(await linesOf(aug.id), 'RATES'));
  const sep = await billing.generateDraft({ organizationId: orgId, leaseId: l1.id, period: '2026-09' });
  const sepRates = allOf(await linesOf(sep.id), 'RATES');
  // September has 30 days: Sep 1–14 at the old rate = 900 × 14/30 = 420.00,
  // Sep 15–30 at the new = 1000 × 16/30 = 533.333… → 533.33. 14 + 16 = 30: every
  // day billed once and no day billed twice.
  ck('J3 September is split in two', sepRates.length === 2, JSON.stringify(sepRates));
  ck('J4 the old rate covers Sep 1–14 = 420.00', sepRates.some((l) => l.amount === '420.00' && l.description.includes('2026-09-01 → 2026-09-14')), JSON.stringify(sepRates));
  ck('J5 the new rate covers Sep 15–30 = 533.33', sepRates.some((l) => l.amount === '533.33' && l.description.includes('2026-09-15 → 2026-09-30')), JSON.stringify(sepRates));
  ck('J6 the two together are 953.33 — no gap, no double charge', sumOf(await linesOf(sep.id), 'RATES') === '953.33', sumOf(await linesOf(sep.id), 'RATES'));
  const oct = await billing.generateDraft({ organizationId: orgId, leaseId: l1.id, period: '2026-10' });
  ck('J7 October, entirely after: 1000.00 on one line',
    sumOf(await linesOf(oct.id), 'RATES') === '1000.00' && allOf(await linesOf(oct.id), 'RATES').length === 1, sumOf(await linesOf(oct.id), 'RATES'));

  console.log('\nK. A whole-month charge refuses to step mid-month rather than bill twice');
  const l7 = await leases.create({ ...base, reference: `${PFX}-L7`, status: 'ACTIVE', unitIds: [U.U3], chargeRules: rules([{ chargeTypeId: ratesCt.id, amount: '900', unitId: U.U3, proration: 'FULL_MONTH' }]) });
  const wholeMonth = await sc.affectedLeases({ id: rates1000.id });
  const l7Row = wholeMonth.affected.find((a) => a.leaseId === l7.id);
  ck('K1 the review flags it instead of offering a clean tick', l7Row?.blockedReason === 'WHOLE_MONTH_MID_MONTH', JSON.stringify(l7Row));
  const blocked = await refused(() => sc.applyToLeases({ id: rates1000.id, targets: [{ leaseId: l7.id, unitId: U.U3 }] }));
  ck('K2 applying it is refused', blocked.includes('start of one of its billing periods'), `got "${blocked}"`);
  ck('K3 and its charges were left alone', (await prisma.chargeRule.count({ where: { leaseId: l7.id } })) === 1);
  // From the 1st it is fine: one occurrence of the charge, one rule billing it.
  const rates1100 = await sc.create({ propertyId: prop.id, chargeTypeId: ratesCt.id, amount: '1100', effectiveFrom: '2026-12-01' });
  const decReview = await sc.affectedLeases({ id: rates1100.id });
  ck('K4 the same charge stepping from the 1st is not blocked', decReview.affected.find((a) => a.leaseId === l7.id)?.blockedReason === null);
  await sc.applyToLeases({ id: rates1100.id, targets: [{ leaseId: l7.id, unitId: U.U3 }] });
  const nov = await billing.generateDraft({ organizationId: orgId, leaseId: l7.id, period: '2026-11' });
  const dec = await billing.generateDraft({ organizationId: orgId, leaseId: l7.id, period: '2026-12' });
  ck('K5 November bills the whole month at the old amount, once', sumOf(await linesOf(nov.id), 'RATES') === '900.00' && allOf(await linesOf(nov.id), 'RATES').length === 1);
  ck('K6 December bills the whole month at the new amount, once', sumOf(await linesOf(dec.id), 'RATES') === '1100.00' && allOf(await linesOf(dec.id), 'RATES').length === 1, sumOf(await linesOf(dec.id), 'RATES'));

  console.log('\nL. A lease edited behind the reviewer’s back is re-derived, never assumed');
  const l8 = await leases.create({ ...base, reference: `${PFX}-L8`, status: 'ACTIVE', unitIds: [U.U5], chargeRules: rules([{ chargeTypeId: mgmtCt.id, amount: '480', unitId: U.U5 }]) });
  const mgmt700 = await sc.create({ propertyId: prop.id, chargeTypeId: mgmtCt.id, amount: '700', effectiveFrom: '2027-01-01' });
  const beforeEdit = await sc.affectedLeases({ id: mgmt700.id });
  ck('L1 the review on screen saw 480', beforeEdit.affected.find((a) => a.leaseId === l8.id)?.currentAmount === '480.00');
  // Somebody saves the lease form meanwhile, which replaces its rules outright —
  // so the row the reviewer ticked no longer exists even by id.
  await leases.update({ ...base, id: l8.id, reference: `${PFX}-L8`, status: 'ACTIVE', unitIds: [U.U5], chargeRules: rules([{ chargeTypeId: mgmtCt.id, amount: '490', unitId: U.U5 }]) });
  // A tick names a lease and a unit, never an amount or a rule id: applying
  // re-reads the tenancy, so it steps what is actually there.
  const raced = await sc.applyToLeases({ id: mgmt700.id, targets: [{ leaseId: l8.id, unitId: U.U5 }] });
  ck('L2 applying steps the 490 that is really there, not the 480 on screen', raced.applied[0]?.previousAmount === '490.00', JSON.stringify(raced.applied));
  const l8Rules = await prisma.chargeRule.findMany({ where: { leaseId: l8.id, chargeTypeId: mgmtCt.id } });
  ck('L3 leaving 490 closed on 2026-12-31 and 700 from 2027-01-01',
    l8Rules.length === 2 && d(l8Rules.find((r) => r.amount.toFixed(2) === '490.00')?.endDate ?? null) === '2026-12-31'
    && d(l8Rules.find((r) => r.amount.toFixed(2) === '700.00')?.startDate ?? null) === '2027-01-01',
    JSON.stringify(l8Rules.map((r) => `${r.amount}:${d(r.startDate)}→${d(r.endDate)}`)));
  ck('L4 the 480 that was on screen was never written anywhere', (await prisma.chargeRule.count({ where: { leaseId: l8.id, amount: '480' } })) === 0);

  console.log('\nM. Correcting and deleting a figure');
  await sc.update({ id: mgmt600.id, amount: '620', effectiveFrom: '2026-07-01', note: 'typo — the letter said 620' });
  const corrected = (await sc.list({ propertyId: prop.id, onDate: '2026-08-01' })).effective;
  ck('M1 the corrected amount is what resolves', eff(corrected, null, mgmtCt.id)?.amount === '620.00', eff(corrected, null, mgmtCt.id)?.amount);
  ck('M2 the charge rule already applied to L1 is NOT rewritten — it is that tenancy’s own terms now',
    (await prisma.chargeRule.count({ where: { leaseId: l1.id, chargeTypeId: mgmtCt.id, amount: '600' } })) === 1);
  const movedOntoAnother = await refused(() => sc.update({ id: mgmt600.id, amount: '620', effectiveFrom: '2026-01-01' }));
  ck('M3 correcting a date onto another row of the same scope is refused', movedOntoAnother.includes('already starts on that date'), `got "${movedOntoAnother}"`);
  await sc.remove({ id: mgmt600.id });
  const afterDelete = (await sc.list({ propertyId: prop.id, onDate: '2026-08-01' })).effective;
  ck('M4 deleting it falls back to the figure before it', eff(afterDelete, null, mgmtCt.id)?.amount === '500.00', eff(afterDelete, null, mgmtCt.id)?.amount);
  ck('M5 and L1 still bills 600 — deleting the record never un-writes a lease',
    (await prisma.chargeRule.count({ where: { leaseId: l1.id, chargeTypeId: mgmtCt.id, amount: '600' } })) === 1);
  const goneReview = await refused(() => sc.affectedLeases({ id: mgmt600.id }));
  ck('M6 the deleted row can no longer be reviewed', goneReview.includes('Standard charge not found'), `got "${goneReview}"`);
  ck('M7 rates history is untouched by all of it', (await sc.list({ propertyId: prop.id })).rows.filter((r) => r.chargeTypeId === ratesCt.id).length === 3);
  void rates900;

  console.log('\nN. Organisation scoping and permissions');
  const org2 = (await prisma.organization.create({ data: { code: OTHER_ORG_CODE, name: 'Standard charge smoke org 2' } })).id;
  const intruder = standardChargesRouter.createCaller(ctxFor(org2, FULL));
  const crossRead = await refused(() => intruder.list({ propertyId: prop.id }));
  ck('N1 another organisation cannot read this property’s figures', crossRead.includes('Property not found'), `got "${crossRead}"`);
  const crossWrite = await refused(() => intruder.create({ propertyId: prop.id, chargeTypeId: mgmtCt.id, amount: '1', effectiveFrom: '2026-01-01' }));
  ck('N2 nor record one against it', crossWrite.includes('Property not found'), `got "${crossWrite}"`);
  const crossReview = await refused(() => intruder.affectedLeases({ id: u1Mgmt.id }));
  ck('N3 nor review one', crossReview.includes('Standard charge not found'), `got "${crossReview}"`);
  const reader = standardChargesRouter.createCaller(ctxFor(orgId, ['property.read', 'lease.read']));
  ck('N4 property.read is enough to look', (await reader.list({ propertyId: prop.id })).rows.length > 0);
  const noWrite = await refused(() => reader.create({ propertyId: prop.id, chargeTypeId: mgmtCt.id, amount: '1', effectiveFrom: '2030-01-01' }));
  ck('N5 recording one needs property.update', noWrite.includes('Missing permission: property.update'), `got "${noWrite}"`);
  const propOnly = standardChargesRouter.createCaller(ctxFor(orgId, ['property.read', 'property.update']));
  const noLeaseUpdate = await refused(() => propOnly.applyToLeases({ id: u1Mgmt.id, targets: [{ leaseId: l2.id, unitId: U.U1 }] }));
  ck('N6 applying to a tenancy needs lease.update, not property.update', noLeaseUpdate.includes('Missing permission: lease.update'), `got "${noLeaseUpdate}"`);
  const noNotice = await refused(() => propOnly.create({
    propertyId: prop.id, chargeTypeId: mgmtCt.id, amount: '999', effectiveFrom: '2030-06-01',
    notice: { date: '2030-05-01', typeId: 'whatever', remark: 'x' },
  }));
  ck('N7 recording the letter alongside it needs notice.create', noNotice.includes('Missing permission: notice.create'), `got "${noNotice}"`);
  ck('N8 and the refused save stored neither', (await prisma.standardCharge.count({ where: { organizationId: orgId, amount: '999' } })) === 0);

  // A building of its own, so a figure recorded here reaches only the tenancies
  // set up below it.
  const extra = await prisma.property.create({
    data: { organizationId: orgId, name: `${PFX} Quarterly Property`, units: { create: [{ name: 'Y1' }, { name: 'Y2' }, { name: 'Y3' }, { name: 'Y4' }] } },
  });
  const Y = Object.fromEntries((await prisma.unit.findMany({ where: { propertyId: extra.id } })).map((u) => [u.name, u.id])) as Record<string, string>;
  const xBase = { ...base, propertyId: extra.id };

  console.log('\nO. A charge the tenancy bills for the WHOLE lease is reported, never offered');
  // The shape every hand-typed rule starts in: one management fee for the
  // tenancy, not one per unit. That amount is the lease's TOTAL — apportioned
  // across the billed units on a split note — so it is not the same kind of
  // number as a per-unit standard figure, and stepping it would reprice every
  // unit on the lease from a decision made about one of them.
  const l9 = await leases.create({
    ...xBase, reference: `${PFX}-L9`, status: 'ACTIVE', unitIds: [Y.Y1, Y.Y2],
    chargeRules: rules([{ chargeTypeId: mgmtCt.id, amount: '2500' }]),
  });
  const extraMgmt = await sc.create({ propertyId: extra.id, chargeTypeId: mgmtCt.id, amount: '600', effectiveFrom: '2026-11-01' });
  const wholeLease = await sc.affectedLeases({ id: extraMgmt.id });
  const l9Skips = wholeLease.skipped.filter((s) => s.leaseId === l9.id);
  ck('O1 it is not offered as a tick', wholeLease.affected.filter((a) => a.leaseId === l9.id).length === 0,
    JSON.stringify(wholeLease.affected.map((a) => `${a.leaseReference}/${a.unitName}`)));
  ck('O2 it is reported ONCE, not once per unit', l9Skips.length === 1, JSON.stringify(l9Skips));
  ck('O3 …as the whole lease, at the amount really charged',
    l9Skips[0]?.reason === 'CHARGED_FOR_THE_WHOLE_LEASE' && l9Skips[0]?.unitId === null && l9Skips[0]?.currentAmount === '2500.00',
    JSON.stringify(l9Skips[0]));
  const wholeLeaseApply = await refused(() => sc.applyToLeases({ id: extraMgmt.id, targets: [{ leaseId: l9.id, unitId: Y.Y1 }] }));
  ck('O4 ticking it anyway is refused', wholeLeaseApply.includes('no longer affected'), `got "${wholeLeaseApply}"`);
  ck('O5 and the tenancy still has its ONE management-fee rule — no successor, no phantom',
    (await prisma.chargeRule.count({ where: { leaseId: l9.id } })) === 1);

  console.log('\nP. A whole-month charge billed every few months may only step at a period boundary');
  const l10 = await leases.create({
    ...xBase, reference: `${PFX}-L10`, status: 'ACTIVE', unitIds: [Y.Y3],
    chargeRules: rules([{ chargeTypeId: ratesCt.id, amount: '3000', unitId: Y.Y3, frequencyMonths: 3, proration: 'FULL_MONTH' }]),
  });
  // The 1st of a month — but the SECOND month of the Oct–Dec quarter. The engine
  // charges a whole-month rule its full amount for however few days it covers,
  // so stepping here would bill the closed rule AND its successor a full quarter
  // each: 6,600.00 for a quarter worth 3,000.00.
  const midQuarter = await sc.create({ propertyId: extra.id, unitId: Y.Y3, chargeTypeId: ratesCt.id, amount: '3600', effectiveFrom: '2026-11-01' });
  const midQuarterRow = (await sc.affectedLeases({ id: midQuarter.id })).affected.find((a) => a.leaseId === l10.id);
  ck('P1 the review flags the 1st of a non-quarter month, not just mid-month',
    midQuarterRow?.blockedReason === 'WHOLE_MONTH_MID_MONTH' && midQuarterRow?.frequencyMonths === 3, JSON.stringify(midQuarterRow));
  const midQuarterApply = await refused(() => sc.applyToLeases({ id: midQuarter.id, targets: [{ leaseId: l10.id, unitId: Y.Y3 }] }));
  ck('P2 applying it is refused', midQuarterApply.includes('start of one of its billing periods'), `got "${midQuarterApply}"`);
  ck('P3 and its charges were left alone', (await prisma.chargeRule.count({ where: { leaseId: l10.id } })) === 1);
  // 2027-01-01 is 12 months after the lease started: 12 % 3 = 0, so it opens a
  // quarter and the step is clean.
  const onBoundary = await sc.create({ propertyId: extra.id, unitId: Y.Y3, chargeTypeId: ratesCt.id, amount: '3900', effectiveFrom: '2027-01-01' });
  ck('P4 the start of a quarter is not blocked',
    (await sc.affectedLeases({ id: onBoundary.id })).affected.find((a) => a.leaseId === l10.id)?.blockedReason === null);
  await sc.applyToLeases({ id: onBoundary.id, targets: [{ leaseId: l10.id, unitId: Y.Y3 }] });
  const q4 = await billing.generateDraft({ organizationId: orgId, leaseId: l10.id, period: '2026-10' });
  const q1 = await billing.generateDraft({ organizationId: orgId, leaseId: l10.id, period: '2027-01' });
  ck('P5 the Oct–Dec quarter is billed once, at the old amount',
    sumOf(await linesOf(q4.id), 'RATES') === '3000.00' && allOf(await linesOf(q4.id), 'RATES').length === 1, sumOf(await linesOf(q4.id), 'RATES'));
  ck('P6 the Jan–Mar quarter is billed once, at the new amount',
    sumOf(await linesOf(q1.id), 'RATES') === '3900.00' && allOf(await linesOf(q1.id), 'RATES').length === 1, sumOf(await linesOf(q1.id), 'RATES'));

  console.log('\nQ. A note whose period STARTS before the change but COVERS it is listed for rebuild');
  const l11 = await leases.create({
    ...xBase, reference: `${PFX}-L11`, status: 'ACTIVE', unitIds: [Y.Y4],
    chargeRules: rules([{ chargeTypeId: ratesCt.id, amount: '3000', unitId: Y.Y4, frequencyMonths: 3 }]),
  });
  // A quarterly note is labelled with the FIRST month of its window, so the
  // Oct–Dec note is "2026-10" and a change from 2026-11-01 lands inside it.
  const octDec = await billing.generateDraft({ organizationId: orgId, leaseId: l11.id, period: '2026-10' });
  ck('Q1 the draft covers Oct–Dec at the old amount', sumOf(await linesOf(octDec.id), 'RATES') === '3000.00');
  const inMidWindow = await sc.create({ propertyId: extra.id, unitId: Y.Y4, chargeTypeId: ratesCt.id, amount: '3600', effectiveFrom: '2026-11-01' });
  ck('Q2 a charge prorated by day is not blocked mid-quarter',
    (await sc.affectedLeases({ id: inMidWindow.id })).affected.find((a) => a.leaseId === l11.id)?.blockedReason === null);
  const midWindowApply = await sc.applyToLeases({ id: inMidWindow.id, targets: [{ leaseId: l11.id, unitId: Y.Y4 }] });
  const listedDraft = midWindowApply.draftInvoices.find((i) => i.id === octDec.id);
  ck('Q3 the note is listed although its period label is before the change',
    Boolean(listedDraft), JSON.stringify(midWindowApply.draftInvoices.map((i) => i.billingPeriod)));
  ck('Q4 …and says it is a draft, so the screen knows it can be rebuilt', listedDraft?.status === 'DRAFT', String(listedDraft?.status));
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: octDec.id });
  const rebuiltLines = allOf(await linesOf(octDec.id), 'RATES');
  // 92 days in the quarter: 3000 × 31/92 = 1010.87 for Oct, 3600 × 61/92 =
  // 2386.96 for Nov–Dec. 31 + 61 = 92 — every day billed once.
  ck('Q5 rebuilding splits the quarter in two', rebuiltLines.length === 2, JSON.stringify(rebuiltLines));
  ck('Q6 …at 1010.87 + 2386.96 = 3397.83', sumOf(await linesOf(octDec.id), 'RATES') === '3397.83', sumOf(await linesOf(octDec.id), 'RATES'));
}

main()
  .catch((e) => { fail++; console.log(`\nFATAL: ${e instanceof Error ? e.stack : e}`); })
  .finally(async () => {
    await purge().catch((e) => console.log('cleanup warn', e instanceof Error ? e.message : e));
    await prisma.$disconnect();
    console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'} — ${pass} passed, ${fail} failed`);
    process.exit(fail === 0 ? 0 : 1);
  });
