/**
 * Functional smoke: rent-free periods.
 *
 * A Hong Kong tenancy often starts rent-free — a fit-out window, or free months
 * given at signing. Until now the office faked it by hand-editing the charge
 * rule's date window, which stopped the charge without recording why and could
 * not say "free rent but still pay the rates".
 *
 * What this proves against the real services:
 *   · the window frees only the charge types flagged for it — management fee and
 *     rates keep billing straight through a fit-out period;
 *   · a month the window covers entirely produces NO rent line, not a 0.00 one;
 *   · a month it covers in half is charged for the days outside it, to the cent;
 *   · rebuilding a draft is idempotent — the same figures, not a second set;
 *   · a window recorded after the draft was raised takes the stale rent line OFF
 *     the note, rather than refusing and leaving a full month still issuable;
 *   · terminating inside the window prorates what is left and skips what is free;
 *   · a renewal does NOT inherit the window (it belongs to the original signing);
 *   · the three ways of typing the window wrong are refused, not stored;
 *   · turning the charge type's flag off bills the very same lease in full;
 *   · a rent-free window frees the RENT and never metered usage — the flag
 *     cannot be ticked on a water/electricity/gas type at all, and a meter
 *     reading inside the window bills in full beside a rent line that is free.
 *
 * Standalone, self-cleaning: its own ZZ organisation, purged at both ends.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/rent-free-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 { MeteringService } from '../src/metering/metering.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { chargeTypesRouter } from '../src/trpc/routers/charge-types.router';
import { leasesRouter } from '../src/trpc/routers/leases.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));
const metering = new MeteringService(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-RF';
const ORG_CODE = `${PFX}-ORG`;
const PERMS = ['lease.read', 'lease.create', 'lease.update', 'charge-type.read', 'charge-type.create', 'charge-type.update'];

function staffCtx(orgId: string): Context {
  const user: AuthUser = { id: 'zz-rf-staff', email: 'zz-rf@rms.local', name: 'ZZ RF', tenantId: null, mustChangePassword: false, roles: ['ADMIN'], permissions: PERMS };
  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),
    meta: (l.meta ?? null) as { rentFree?: { from: string; to: string; days: number; billedDays: number; totalDays: number } } | null,
  }));
}
const totalOf = async (invoiceId: string) =>
  (await prisma.invoiceLine.findMany({ where: { invoiceId }, select: { amount: true } }))
    .reduce((s, l) => s + Number(l.amount), 0)
    .toFixed(2);
const find = (lines: Awaited<ReturnType<typeof linesOf>>, code: string) => lines.find((l) => l.code === code);

async function purge() {
  const org = await prisma.organization.findUnique({ where: { code: ORG_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 } } });
  }
  if (leaseIds.length) {
    await prisma.chargeRule.deleteMany({ where: { leaseId: { in: leaseIds } } });
    await prisma.leaseUnit.deleteMany({ where: { leaseId: { in: leaseIds } } });
    // Renewals point back at what they renewed; cut the link before deleting.
    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 } });
  // Meters hold down both the units they cover and the charge type they measure
  // (onDelete: Restrict on each), and their readings hold down the meter — so
  // this rung comes before the units and the charge types below. Tariffs go with
  // the property and the charge type by cascade.
  const meters = await prisma.meter.findMany({
    where: { units: { some: { unit: { propertyId: { in: props.map((p) => p.id) } } } } },
    select: { id: true },
  });
  if (meters.length) {
    const meterIds = meters.map((m) => m.id);
    await prisma.meterReading.deleteMany({ where: { meterId: { in: meterIds } } });
    await prisma.meterUnit.deleteMany({ where: { meterId: { in: meterIds } } });
    await prisma.meter.deleteMany({ where: { id: { in: meterIds } } });
  }
  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.organization.delete({ where: { id: org.id } });
}

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'Rent-free smoke org' } })).id;
  const leases = leasesRouter.createCaller(staffCtx(orgId));
  const chargeTypes = chargeTypesRouter.createCaller(staffCtx(orgId));

  const glDefs = [
    { 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 },
    { code: '2200', name: 'Utilities Payable', type: 'LIABILITY' as const },
  ];
  const gl: Record<string, string> = {};
  for (const g of glDefs) gl[g.code] = (await prisma.glAccount.create({ data: { organizationId: orgId, ...g } })).id;
  // Its own prefix: Invoice.number is unique across the whole database, and the
  // smokes share one, so a plain "DN-" would collide with the office's notes.
  await prisma.numberSequence.create({ data: { organizationId: orgId, docType: 'INVOICE', prefix: 'ZZRF-', padding: 6 } });

  // The owner's rule, expressed as configuration: a rent-free period frees the
  // rent and nothing else.
  const rentCt = await chargeTypes.create({ code: 'RENT', nameEn: 'Rent', nameZh: '租金', category: 'RECURRING', glAccountId: gl['4000'], waivedDuringRentFree: true, sortOrder: 0 });
  const mgmtCt = await chargeTypes.create({ code: 'MGMT_FEE', nameEn: 'Management Fee', nameZh: '管理費', category: 'RECURRING', glAccountId: gl['4100'], sortOrder: 1 });
  const ratesCt = await chargeTypes.create({ code: 'RATES', nameEn: 'Government Rates', nameZh: '差餉', category: 'RECURRING', glAccountId: gl['2100'], sortOrder: 2 });

  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: `${PFX} U1` } } } });
  const unit = await prisma.unit.findFirstOrThrow({ where: { propertyId: prop.id } });

  const rules = [
    { chargeTypeId: rentCt.id, amount: '31000', frequencyMonths: 1, timing: 'ADVANCE' as const, proration: 'DAILY' as const, firstInvoiceOnly: false },
    { chargeTypeId: mgmtCt.id, amount: '3100', frequencyMonths: 1, timing: 'ADVANCE' as const, proration: 'FULL_MONTH' as const, firstInvoiceOnly: false },
    { chargeTypeId: ratesCt.id, amount: '900', frequencyMonths: 1, timing: 'ADVANCE' as const, proration: 'DAILY' as const, firstInvoiceOnly: false },
  ];

  console.log('A. A lease records one rent-free window and reads it back');
  const a = await leases.create({
    reference: `${PFX}-A`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
    startDate: '2026-01-01', endDate: '2027-12-31', depositMonths: 0,
    rentFreeFrom: '2026-01-01', rentFreeTo: '2026-02-15',
    unitIds: [unit.id], chargeRules: rules,
  });
  const gotA = await leases.get({ id: a.id });
  ck('A1 the window round-trips as plain dates', gotA.rentFreeFrom === '2026-01-01' && gotA.rentFreeTo === '2026-02-15', `got ${gotA.rentFreeFrom} → ${gotA.rentFreeTo}`);
  const form = await leases.formData();
  ck('A2 the form is told which charges the window frees', form.chargeTypes.find((c) => c.id === rentCt.id)?.waivedDuringRentFree === true
    && form.chargeTypes.find((c) => c.id === mgmtCt.id)?.waivedDuringRentFree === false);

  console.log('\nB. A month the window covers entirely: no rent line at all');
  const jan = await billing.generateDraft({ organizationId: orgId, leaseId: a.id, period: '2026-01' });
  const janLines = await linesOf(jan.id);
  ck('B1 no rent line — not a 0.00 one', find(janLines, 'RENT') === undefined, JSON.stringify(janLines.map((l) => l.code)));
  ck('B2 the management fee is charged in full', find(janLines, 'MGMT_FEE')?.amount === '3100.00', find(janLines, 'MGMT_FEE')?.amount);
  ck('B3 so are the rates', find(janLines, 'RATES')?.amount === '900.00', find(janLines, 'RATES')?.amount);
  ck('B4 the note totals 4000.00', (await totalOf(jan.id)) === '4000.00', await totalOf(jan.id));

  console.log('\nC. A month it covers in half: charged for the days outside it');
  // Feb 2026 = 28 days; free Feb 1–15 = 15 → 13 × 31000/28 = 14392.857… → 14392.86
  const feb = await billing.generateDraft({ organizationId: orgId, leaseId: a.id, period: '2026-02' });
  const febLines = await linesOf(feb.id);
  ck('C1 rent is 13 of 28 days = 14392.86', find(febLines, 'RENT')?.amount === '14392.86', find(febLines, 'RENT')?.amount);
  ck('C2 the line says why it is short', find(febLines, 'RENT')?.description === 'Rent · 2026-02 — rent-free 2026-02-01 → 2026-02-15 (15 day(s) not charged)', find(febLines, 'RENT')?.description);
  const febMeta = find(febLines, 'RENT')?.meta?.rentFree;
  ck('C3 and carries the days in meta, clipped to the month',
    febMeta?.from === '2026-02-01' && febMeta?.to === '2026-02-15' && febMeta?.days === 15 && febMeta?.billedDays === 13 && febMeta?.totalDays === 28,
    JSON.stringify(find(febLines, 'RENT')?.meta));
  ck('C4 the other two charges are untouched', find(febLines, 'MGMT_FEE')?.amount === '3100.00' && find(febLines, 'RATES')?.amount === '900.00');
  ck('C5 and neither carries rent-free meta', !find(febLines, 'MGMT_FEE')?.meta && !find(febLines, 'RATES')?.meta);
  ck('C6 the note totals 18392.86', (await totalOf(feb.id)) === '18392.86', await totalOf(feb.id));

  console.log('\nD. The first month after the window bills in full');
  const mar = await billing.generateDraft({ organizationId: orgId, leaseId: a.id, period: '2026-03' });
  const marLines = await linesOf(mar.id);
  ck('D1 full rent', find(marLines, 'RENT')?.amount === '31000.00', find(marLines, 'RENT')?.amount);
  ck('D2 with the ordinary wording', find(marLines, 'RENT')?.description === 'Rent · 2026-03', find(marLines, 'RENT')?.description);
  ck('D3 the note totals 35000.00', (await totalOf(mar.id)) === '35000.00', await totalOf(mar.id));

  console.log('\nE. Rebuilding the half-free month is idempotent');
  const r1 = await billing.regenerateDraft({ organizationId: orgId, invoiceId: feb.id });
  ck('E1 the rebuild reports the same total', r1.total === '18392.86', JSON.stringify(r1));
  const r2 = await billing.regenerateDraft({ organizationId: orgId, invoiceId: feb.id });
  ck('E2 rebuilding twice changes nothing', r2.total === '18392.86' && r2.replaced === r1.replaced, JSON.stringify(r2));
  const rebuilt = await linesOf(feb.id);
  ck('E3 still exactly three lines — nothing double-counted', rebuilt.length === 3, JSON.stringify(rebuilt.map((l) => `${l.code}=${l.amount}`)));
  ck('E4 and rent is still 14392.86', find(rebuilt, 'RENT')?.amount === '14392.86', find(rebuilt, 'RENT')?.amount);

  console.log('\nF. Turning the charge type’s flag off bills the same lease in full');
  await chargeTypes.update({ id: rentCt.id, waivedDuringRentFree: false });
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: feb.id });
  const unwaived = await linesOf(feb.id);
  ck('F1 rent is the whole month again', find(unwaived, 'RENT')?.amount === '31000.00', find(unwaived, 'RENT')?.amount);
  ck('F2 with no rent-free note on the line', !find(unwaived, 'RENT')?.meta, JSON.stringify(find(unwaived, 'RENT')?.meta));
  await chargeTypes.update({ id: rentCt.id, waivedDuringRentFree: true });
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: feb.id });
  ck('F3 switching it back on restores the short rent', find(await linesOf(feb.id), 'RENT')?.amount === '14392.86');

  console.log('\nG. A short-billed note issues and posts what it says');
  const issued = await billing.issue({ organizationId: orgId, invoiceId: feb.id });
  const arLines = await prisma.journalLine.findMany({ where: { invoiceId: issued.id, accountId: gl['1100'] }, select: { direction: true, amount: true } });
  ck('G1 AR is debited the note total, not the full rent', arLines.length === 1 && arLines[0].direction === 'DEBIT' && arLines[0].amount.toFixed(2) === '18392.86', JSON.stringify(arLines.map((l) => `${l.direction} ${l.amount}`)));

  console.log('\nH. Terminating inside the window');
  const b = await leases.create({
    reference: `${PFX}-B`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
    startDate: '2026-01-01', endDate: '2027-12-31', depositMonths: 0,
    rentFreeFrom: '2026-01-01', rentFreeTo: '2026-03-31',
    unitIds: [unit.id], chargeRules: rules,
  });
  const termB = await billing.terminateLease({ organizationId: orgId, leaseId: b.id, terminationDate: new Date('2026-02-10T00:00:00.000Z'), reason: 'fit-out abandoned' });
  ck('H1 a final note is still raised', termB.finalInvoiceId !== null && termB.finalInvoiceSkipped === null, JSON.stringify(termB));
  const bLines = await linesOf(termB.finalInvoiceId!);
  ck('H2 no rent — every covered day was free', find(bLines, 'RENT') === undefined, JSON.stringify(bLines.map((l) => `${l.code}=${l.amount}`)));
  ck('H3 the FULL_MONTH management fee is still whole', find(bLines, 'MGMT_FEE')?.amount === '3100.00', find(bLines, 'MGMT_FEE')?.amount);
  // Rates are DAILY and not waived: Feb 1–10 of 28 → 900 × 10/28 = 321.4285… → 321.43
  ck('H4 the rates are prorated to the termination date', find(bLines, 'RATES')?.amount === '321.43', find(bLines, 'RATES')?.amount);

  // A rent-only tenancy that stops inside its fit-out period has nothing left
  // to bill — reported, not thrown, exactly as an already-billed month is.
  const c = await leases.create({
    reference: `${PFX}-C`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
    startDate: '2026-01-01', endDate: '2027-12-31', depositMonths: 0,
    rentFreeFrom: '2026-01-01', rentFreeTo: '2026-06-30',
    unitIds: [unit.id], chargeRules: [rules[0]],
  });
  const termC = await billing.terminateLease({ organizationId: orgId, leaseId: c.id, terminationDate: new Date('2026-04-15T00:00:00.000Z') });
  ck('H5 a rent-only lease that stops mid-window reports NOTHING_TO_BILL', termC.finalInvoiceId === null && termC.finalInvoiceSkipped === 'NOTHING_TO_BILL', JSON.stringify(termC));
  ck('H6 and it is terminated all the same', (await prisma.lease.findUniqueOrThrow({ where: { id: c.id } })).status === 'TERMINATED');

  console.log('\nI. A renewal does not inherit the window');
  const renewal = await leases.create({
    reference: `${PFX}-A-R`, tenantId: tenant.id, status: 'DRAFT', currency: 'HKD',
    startDate: '2028-01-01', endDate: '2029-12-31', depositMonths: 0,
    renewedFromId: a.id, unitIds: [unit.id], chargeRules: rules,
  });
  const gotR = await leases.get({ id: renewal.id });
  ck('I1 the renewal has no rent-free window', gotR.rentFreeFrom === null && gotR.rentFreeTo === null, `${gotR.rentFreeFrom} → ${gotR.rentFreeTo}`);
  ck('I2 while the lease it renews still has its own', (await leases.get({ id: a.id })).rentFreeFrom === '2026-01-01');
  const renewJan = await billing.generateDraft({ organizationId: orgId, leaseId: renewal.id, period: '2028-01' });
  ck('I3 its first month bills the full rent', find(await linesOf(renewJan.id), 'RENT')?.amount === '31000.00', find(await linesOf(renewJan.id), 'RENT')?.amount);

  console.log('\nJ. The three ways of typing it wrong are refused');
  const base = {
    tenantId: tenant.id, status: 'ACTIVE' as const, currency: 'HKD' as const,
    startDate: '2026-01-01', endDate: '2026-12-31', depositMonths: 0, unitIds: [unit.id], chargeRules: rules,
  };
  const halfWindow = await refused(() => leases.create({ ...base, reference: `${PFX}-X1`, rentFreeFrom: '2026-01-01' }));
  ck('J1 a start with no end is refused', halfWindow.includes('needs both a start and an end date'), `got "${halfWindow}"`);
  const halfWindow2 = await refused(() => leases.create({ ...base, reference: `${PFX}-X2`, rentFreeTo: '2026-01-31' }));
  ck('J2 an end with no start too', halfWindow2.includes('needs both a start and an end date'), `got "${halfWindow2}"`);
  const backwards = await refused(() => leases.create({ ...base, reference: `${PFX}-X3`, rentFreeFrom: '2026-03-31', rentFreeTo: '2026-03-01' }));
  ck('J3 a backwards window is refused', backwards.includes('cannot end before it starts'), `got "${backwards}"`);
  const outside = await refused(() => leases.create({ ...base, reference: `${PFX}-X4`, rentFreeFrom: '2025-01-01', rentFreeTo: '2025-02-01' }));
  ck('J4 a window entirely before the term is refused', outside.includes('must overlap the lease term'), `got "${outside}"`);
  const outsideAfter = await refused(() => leases.create({ ...base, reference: `${PFX}-X5`, rentFreeFrom: '2027-01-01', rentFreeTo: '2027-02-01' }));
  ck('J5 and entirely after it', outsideAfter.includes('must overlap the lease term'), `got "${outsideAfter}"`);
  ck('J6 none of the five was stored', (await prisma.lease.count({ where: { organizationId: orgId, reference: { startsWith: `${PFX}-X` } } })) === 0);

  // A window that runs past an end of the term is legitimate — "free until the
  // 15th" is written from the 1st — and only the covered days are freed.
  const d = await leases.create({
    ...base, reference: `${PFX}-D`, startDate: '2026-06-16', endDate: '2027-12-31',
    rentFreeFrom: '2026-06-01', rentFreeTo: '2026-06-20',
  });
  const dJun = await billing.generateDraft({ organizationId: orgId, leaseId: d.id, period: '2026-06' });
  const dLines = await linesOf(dJun.id);
  // Covered Jun 16–30 = 15 days, 5 of them free → 10 × 31000/30 = 10333.33
  ck('J7 a window overhanging the start frees only the covered days', find(dLines, 'RENT')?.amount === '10333.33', find(dLines, 'RENT')?.amount);
  ck('J8 the line names the clipped window', find(dLines, 'RENT')?.meta?.rentFree?.from === '2026-06-16' && find(dLines, 'RENT')?.meta?.rentFree?.days === 5, JSON.stringify(find(dLines, 'RENT')?.meta));

  console.log('\nK. The window can be edited and cleared');
  await leases.update({
    id: a.id, reference: `${PFX}-A`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
    startDate: '2026-01-01', endDate: '2027-12-31', depositMonths: 0,
    rentFreeFrom: '2026-01-01', rentFreeTo: '2026-01-20', unitIds: [unit.id], chargeRules: rules,
  });
  ck('K1 a shortened window is stored', (await leases.get({ id: a.id })).rentFreeTo === '2026-01-20');
  const moved = await refused(() => leases.update({
    id: a.id, reference: `${PFX}-A`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
    startDate: '2027-01-01', endDate: '2027-12-31', depositMonths: 0,
    rentFreeFrom: '2026-01-01', rentFreeTo: '2026-01-20', unitIds: [unit.id], chargeRules: rules,
  }));
  ck('K2 moving the term off the window is refused', moved.includes('must overlap the lease term'), `got "${moved}"`);
  await leases.update({
    id: a.id, reference: `${PFX}-A`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
    startDate: '2026-01-01', endDate: '2027-12-31', depositMonths: 0, unitIds: [unit.id], chargeRules: rules,
  });
  const cleared = await leases.get({ id: a.id });
  ck('K3 it can be cleared altogether', cleared.rentFreeFrom === null && cleared.rentFreeTo === null);
  // The very month that produced no rent line at all in B.
  const janAgain = await billing.generateDraft({ organizationId: orgId, leaseId: a.id, period: '2026-01' });
  ck('K4 and the month that was free now bills in full', find(await linesOf(janAgain.id), 'RENT')?.amount === '31000.00', find(await linesOf(janAgain.id), 'RENT')?.amount);

  console.log('\nL. A window recorded AFTER the draft was raised takes the rent off');
  // The everyday order of events: the monthly run raises the draft, the signed
  // tenancy arrives later with its fit-out period. Rebuilding must REMOVE the
  // stale full-rent line, not refuse — a refusal leaves a note that still says
  // 31000.00 and can still be issued. Rent-only, so the rebuild empties the note
  // entirely; that is the case a lease with other charges never reaches.
  const e = await leases.create({
    reference: `${PFX}-E`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
    startDate: '2026-01-01', endDate: '2027-12-31', depositMonths: 0,
    unitIds: [unit.id], chargeRules: [rules[0]],
  });
  const may = await billing.generateDraft({ organizationId: orgId, leaseId: e.id, period: '2026-05' });
  ck('L1 the draft first bills the full month', find(await linesOf(may.id), 'RENT')?.amount === '31000.00', find(await linesOf(may.id), 'RENT')?.amount);
  await leases.update({
    id: e.id, reference: `${PFX}-E`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
    startDate: '2026-01-01', endDate: '2027-12-31', depositMonths: 0,
    rentFreeFrom: '2026-05-01', rentFreeTo: '2026-05-31', unitIds: [unit.id], chargeRules: [rules[0]],
  });
  const rebuiltE = await refused(() => billing.regenerateDraft({ organizationId: orgId, invoiceId: may.id }));
  ck('L2 the rebuild is not refused', rebuiltE === '', `got "${rebuiltE}"`);
  ck('L3 the stale rent line is gone', (await linesOf(may.id)).length === 0, JSON.stringify(await linesOf(may.id)));
  ck('L4 and the note totals 0.00, not 31000.00', (await totalOf(may.id)) === '0.00', await totalOf(may.id));

  // A note with nothing on it at all still has nothing to rebuild.
  const empty = await refused(() => billing.regenerateDraft({ organizationId: orgId, invoiceId: may.id }));
  ck('L5 rebuilding the now-empty note is refused', empty.includes('No charges apply for 2026-05'), `got "${empty}"`);

  console.log('\nM. The window frees the rent; it never frees what the meter measured');
  // The owner's rule, and the one the engine can actually keep: a metered charge
  // is raised from a dial reading and a tariff by billing's metered path, which
  // never looks at the lease's rent-free window. So the flag cannot be ticked on
  // a utility type at all — the screen must not promise what the note will not do.
  const waterCt = await chargeTypes.create({ code: 'WATER', nameEn: 'Water', nameZh: '水費', category: 'UTILITY', glAccountId: gl['2200'], sortOrder: 3 });
  const tickedOnCreate = await refused(() =>
    chargeTypes.create({ code: 'ELECTRICITY', nameEn: 'Electricity', category: 'UTILITY', glAccountId: gl['2200'], waivedDuringRentFree: true, sortOrder: 4 }),
  );
  ck('M1 ticking the waiver on a new utility charge type is refused', tickedOnCreate.includes('billed on what the meter says was used'), `got "${tickedOnCreate}"`);
  ck('M2 and nothing was stored', (await prisma.chargeType.count({ where: { organizationId: orgId, code: 'ELECTRICITY' } })) === 0);
  const tickedOnUpdate = await refused(() => chargeTypes.update({ id: waterCt.id, waivedDuringRentFree: true }));
  ck('M3 ticking it on an existing one is refused too', tickedOnUpdate.includes('billed on what the meter says was used'), `got "${tickedOnUpdate}"`);
  ck('M4 and the flag is still off', (await prisma.chargeType.findUniqueOrThrow({ where: { id: waterCt.id } })).waivedDuringRentFree === false);
  // The same forbidden row reached from the other side: rent carries the flag,
  // so it cannot be recategorised into a utility while it does.
  const recategorised = await refused(() => chargeTypes.update({ id: rentCt.id, category: 'UTILITY' }));
  ck('M5 moving a waived charge type into UTILITY is refused', recategorised.includes('billed on what the meter says was used'), `got "${recategorised}"`);
  ck('M6 and rent is still RECURRING', (await prisma.chargeType.findUniqueOrThrow({ where: { id: rentCt.id } })).category === 'RECURRING');

  // And the billing half of the same rule, so a later change cannot quietly
  // reverse the owner's decision: a tenancy sitting inside its fit-out window
  // pays nothing for the flat, and every drop of water it used.
  await prisma.utilityTariff.create({ data: { chargeTypeId: waterCt.id, propertyId: prop.id, unitRate: '5', fixedCharge: '0' } });
  const meter = await prisma.meter.create({ data: { chargeTypeId: waterCt.id, serialNo: `${PFX}-W1`, units: { create: { unitId: unit.id } } } });
  const f = await leases.create({
    reference: `${PFX}-F`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
    startDate: '2026-01-01', endDate: '2027-12-31', depositMonths: 0,
    rentFreeFrom: '2026-01-01', rentFreeTo: '2026-12-31',
    unitIds: [unit.id],
    // Amount 0 is how a lease says "this one is billed by meter".
    chargeRules: [rules[0], { chargeTypeId: waterCt.id, amount: '0', frequencyMonths: 1, timing: 'ARREARS' as const, proration: 'FULL_MONTH' as const, firstInvoiceOnly: false }],
  });
  const read = await metering.createReading({ organizationId: orgId, meterId: meter.id, readingStart: '0', readingEnd: '40', periodStart: '2026-05-01', periodEnd: '2026-05-31' });
  ck('M7 the reading is priced at 40 × 5', read.grossAmount?.toFixed(2) === '200.00', `got ${read.grossAmount}`);
  // Utilities bill in arrears: May's usage lands on the June note.
  const jun = await billing.generateDraft({ organizationId: orgId, leaseId: f.id, period: '2026-06' });
  const junLines = await linesOf(jun.id);
  ck('M8 the rent is free for the month', find(junLines, 'RENT') === undefined, JSON.stringify(junLines.map((l) => `${l.code}=${l.amount}`)));
  ck('M9 the water is billed in full all the same', find(junLines, 'WATER')?.amount === '200.00', find(junLines, 'WATER')?.amount);
  ck('M10 and carries no rent-free note', !find(junLines, 'WATER')?.meta?.rentFree, JSON.stringify(find(junLines, 'WATER')?.meta));
  ck('M11 the note totals 200.00', (await totalOf(jun.id)) === '200.00', await totalOf(jun.id));
}

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);
  });
