/**
 * Functional smoke for utility rates set per property.
 *
 * Water in one building does not cost what it costs in the next, so a rate
 * belongs to a property and there is no organisation-wide fallback. What has to
 * hold: every reading is priced at its own property's rate — a master re-priced
 * at billing included — and a property with no rate leaves its readings
 * unpriced and visibly blocked until the rate is set, which then prices them.
 * They used to be stored as zero instead, which billed as nothing and stayed
 * zero after the rate was set; C, D and E are the assertions that matter. The
 * meter rules that keep "the property a meter is in" well defined are driven
 * through the router, where the screens go.
 *
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/tariff-per-property-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import type { Prisma } from '@prisma/client';
import { BillingService } from '../src/billing/billing.service';
import { ApprovalService } from '../src/approvals/approval.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 { meteringRouter } from '../src/trpc/routers/metering.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}`)); };

const REF = 'ZZ-TPP';
const SERIAL = 'ZZ-TPP-';
const PROP = 'ZZ TPP';
const TENANT = 'ZZ TPP Tenant';
const CT_CODE = 'ZZTPPW';
const OTHER_CT_CODE = 'ZZTPPX';
const OTHER_ORG = 'ZZ-TPP-ORG';

const PERMS = ['meter-reading.read', 'meter-reading.create', 'meter-reading.update'];

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

async function refused(fn: () => Promise<unknown>): Promise<string> {
  try {
    await fn();
    return '';
  } catch (e) {
    return e instanceof Error ? e.message : String(e);
  }
}

const grossOf = async (id: string) =>
  (await prisma.meterReading.findUniqueOrThrow({ where: { id }, select: { grossAmount: true } })).grossAmount?.toFixed(2) ?? null;

const billedOn = async (id: string) =>
  (await prisma.meterReading.findUniqueOrThrow({ where: { id }, select: { claims: { select: { invoiceId: true } } } })).claims[0]?.invoiceId ?? null;

/** The metered lines on a note — every one of them records its reading. */
const meteredLines = async (invoiceId: string) =>
  (await prisma.invoiceLine.findMany({ where: { invoiceId }, select: { amount: true, meta: true } }))
    .map((l) => ({ amount: l.amount.toString(), meta: (l.meta ?? {}) as Record<string, unknown> }))
    .filter((l) => typeof l.meta.meterReadingId === 'string');

/** Why a reading is not billed, as the metering page would show it. */
async function blockOf(orgId: string, id: string) {
  const rows = await prisma.meterReading.findMany({
    where: { id },
    select: { id: true, meterId: true, periodStart: true, periodEnd: true, readingStart: true, readingEnd: true, grossAmount: true, status: true, claims: { select: { unitId: true } } },
  });
  return (await metering.explainUnbilled(orgId, rows, new Date('2020-06-15'))).get(id)?.code;
}

async function main() {
  const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
  if (!org) throw new Error('no org');
  const orgId = org.id;
  const rentCt = await prisma.chargeType.findFirst({ where: { organizationId: orgId, category: 'RECURRING', glAccountId: { not: null }, isActive: true }, select: { id: true } });
  if (!rentCt) throw new Error('no rent charge type');

  await purgeStale();

  const water = await prisma.chargeType.create({ data: { organizationId: orgId, code: CT_CODE, nameEn: 'ZZ TPP Water', category: 'UTILITY', isActive: true, sortOrder: 996 } });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: TENANT } });

  const mkProperty = (name: string, units: string[]) =>
    prisma.property.create({
      data: { organizationId: orgId, name: `${PROP} ${name}`, units: { create: units.map((u) => ({ name: `ZZ TPP ${u}` })) } },
      include: { units: true },
    });
  const harbour = await mkProperty('Harbour', ['H1', 'H2', 'H3']);
  const hill = await mkProperty('Hill', ['K1', 'K2']);
  const bare = await mkProperty('Bare', ['B1']);
  const [h1, h2, h3] = harbour.units;
  const [k1, k2] = hill.units;
  const [b1] = bare.units;
  const gone = await prisma.property.create({ data: { organizationId: orgId, name: `${PROP} Gone`, deletedAt: new Date() } });

  // Somebody else's property and utility to aim a rate at. The organisation is
  // created already archived, so the smokes that take "the first live
  // organisation" can never pick it up, even if this run dies before cleanup.
  const otherOrg = await prisma.organization.create({ data: { code: OTHER_ORG, name: 'ZZ TPP other org', deletedAt: new Date() } });
  const otherProperty = await prisma.property.create({ data: { organizationId: otherOrg.id, name: `${PROP} Elsewhere` } });
  const otherWater = await prisma.chargeType.create({ data: { organizationId: otherOrg.id, code: OTHER_CT_CODE, nameEn: 'ZZ TPP Other Water', category: 'UTILITY' } });

  const mkLease = (ref: string, propertyId: string, unitId: string) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `${REF}-${ref}`, tenantId: tenant.id,
        status: 'ACTIVE', currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
        units: { create: [{ unitId }] },
        chargeRules: { create: [
          { chargeTypeId: rentCt.id, amount: '10000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 },
          { chargeTypeId: water.id, amount: '0', frequencyMonths: 1, timing: 'ARREARS', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 1 },
        ] },
      },
    });
  const leaseHarbour = await mkLease('H', harbour.id, h1.id);
  const leaseHill = await mkLease('K', hill.id, k1.id);
  const leaseBare = await mkLease('B', bare.id, b1.id);

  const api = meteringRouter.createCaller(staffCtx(orgId));
  const mkMeter = async (serial: string, unitIds: string[], subMeterIds: string[] = []) =>
    (await api.createMeter({ chargeTypeId: water.id, serialNo: SERIAL + serial, unitIds, subMeterIds })).id;
  const read = async (meterId: string, from: string, to: string, start: string, end: string) =>
    (await api.createReading({ meterId, readingStart: start, readingEnd: end, periodStart: from, periodEnd: to })).id;
  const draft = async (leaseId: string, period: string) => (await billing.generateDraft({ organizationId: orgId, leaseId, period })).id;
  const editorCell = async (propertyId: string) =>
    (await api.tariffs()).find((t) => t.chargeTypeId === water.id)?.properties.find((p) => p.propertyId === propertyId);

  console.log('Fixture: Harbour at 2/unit + 10, Hill at 5/unit, Bare with no rate\n');

  console.log('A. Each property prices its readings at its own rate');
  await api.upsertTariff({ chargeTypeId: water.id, propertyId: harbour.id, unitRate: '2', fixedCharge: '10' });
  await api.upsertTariff({ chargeTypeId: water.id, propertyId: hill.id, unitRate: '5', fixedCharge: '0' });
  const sub = await mkMeter('H-SUB', [h2.id]);
  const master = await mkMeter('H-MASTER', [h1.id], [sub]);
  const hillMeter = await mkMeter('K-1', [k1.id]);
  const masterRead = await read(master, '2019-12-01', '2019-12-31', '0', '100');
  const subRead = await read(sub, '2019-12-01', '2019-12-31', '0', '30');
  const hillRead = await read(hillMeter, '2019-12-01', '2019-12-31', '0', '100');
  ck('A1 Harbour is priced at Harbour’s rate (100 × 2 + 10)', (await grossOf(masterRead)) === '210.00', `got ${await grossOf(masterRead)}`);
  ck('A2 the same usage in Hill at Hill’s (100 × 5)', (await grossOf(hillRead)) === '500.00', `got ${await grossOf(hillRead)}`);
  ck('A3 a sub-meter at its own property’s rate (30 × 2 + 10)', (await grossOf(subRead)) === '70.00', `got ${await grossOf(subRead)}`);
  const harbourCell = await editorCell(harbour.id);
  const hillCell = await editorCell(hill.id);
  ck('A4 the editor lists each live property under the utility', Boolean(harbourCell && hillCell && (await editorCell(bare.id))) && !(await editorCell(gone.id)));
  ck('A5 with its own rate', harbourCell?.unitRate === '2' && harbourCell.fixedCharge === '10' && hillCell?.unitRate === '5', `got ${JSON.stringify([harbourCell, hillCell])}`);
  ck('A6 and the meters that depend on it', harbourCell?.meterCount === 2 && hillCell?.meterCount === 1, `got ${harbourCell?.meterCount}/${hillCell?.meterCount}`);
  const meterRows = await api.meters();
  ck('A7 each meter says which property prices it', meterRows.find((m) => m.id === master)?.propertyId === harbour.id && meterRows.find((m) => m.id === hillMeter)?.propertyId === hill.id);

  console.log('\nB. Each lease’s note carries its own property’s amounts');
  const noteHarbour = await draft(leaseHarbour.id, '2020-01');
  const harbourLines = await meteredLines(noteHarbour);
  // 100 on the master less 30 on the sub-meter leaves 70, at Harbour's 2 + 10.
  // At Hill's rate it would be 350, and unreduced it would be 210.
  ck('B1 the master is re-priced at its property’s rate (70 × 2 + 10)', harbourLines.length === 1 && harbourLines[0].amount === '150', `got ${harbourLines.map((l) => l.amount)}`);
  ck('B2 from the usage left after the sub-meter', String(harbourLines[0]?.meta.usage) === '70', `got ${harbourLines[0]?.meta.usage}`);
  const hillLines = await meteredLines(await draft(leaseHill.id, '2020-01'));
  ck('B3 the Hill lease at Hill’s rate', hillLines.length === 1 && hillLines[0].amount === '500', `got ${hillLines.map((l) => l.amount)}`);

  console.log('\nC. A property with no rate leaves its readings unpriced, not zero');
  const bareMeter = await mkMeter('B-1', [b1.id]);
  const bareRead = await read(bareMeter, '2019-12-01', '2019-12-31', '0', '40');
  ck('C1 the reading carries no amount', (await grossOf(bareRead)) === null, `got ${await grossOf(bareRead)}`);
  ck('C2 and says it has no rate', (await blockOf(orgId, bareRead)) === 'NO_TARIFF', `got ${await blockOf(orgId, bareRead)}`);
  ck('C3 the note does not bill it', (await meteredLines(await draft(leaseBare.id, '2020-01'))).length === 0);
  ck('C4 and leaves it in the queue', (await billedOn(bareRead)) === null);
  const bareCell = await editorCell(bare.id);
  ck('C5 the editor shows the missing rate where a meter needs one', bareCell?.hasTariff === false && bareCell.unitRate === '0' && bareCell.meterCount === 1, `got ${JSON.stringify(bareCell)}`);

  console.log('\nD. Setting the rate prices what was waiting, and the next note bills it');
  await api.upsertTariff({ chargeTypeId: water.id, propertyId: bare.id, unitRate: '3', fixedCharge: '0' });
  ck('D1 the reading is priced at the new rate (40 × 3)', (await grossOf(bareRead)) === '120.00', `got ${await grossOf(bareRead)}`);
  ck('D2 nothing holds it back any more', (await blockOf(orgId, bareRead)) === undefined, `got ${await blockOf(orgId, bareRead)}`);
  const noteBare = await draft(leaseBare.id, '2020-02');
  const bareLines = await meteredLines(noteBare);
  ck('D3 the next note bills it', bareLines.length === 1 && bareLines[0].amount === '120', `got ${bareLines.map((l) => l.amount)}`);
  ck('D4 and claims it', (await billedOn(bareRead)) === noteBare);

  console.log('\nE. A declaration confirmed while there is no rate waits for one');
  const pricedEarlier = await read(bareMeter, '2020-01-01', '2020-01-31', '40', '50');
  await api.deleteTariff({ chargeTypeId: water.id, propertyId: bare.id });
  ck('E1 clearing the rate leaves an amount already set alone (10 × 3)', (await grossOf(pricedEarlier)) === '30.00', `got ${await grossOf(pricedEarlier)}`);
  // Billing bills a priced reading at its stored amount whatever the rate is
  // now, so the list must not claim it is waiting for one.
  ck('E2 and, since that amount still bills, nothing is shown holding it back', (await blockOf(orgId, pricedEarlier)) === undefined, `got ${await blockOf(orgId, pricedEarlier)}`);
  const noteCleared = await draft(leaseBare.id, '2020-03');
  const clearedLines = await meteredLines(noteCleared);
  ck('E3 and the next note does bill it', clearedLines.length === 1 && clearedLines[0].amount === '30' && (await billedOn(pricedEarlier)) === noteCleared, `got ${clearedLines.map((l) => l.amount)}`);
  const declared = await prisma.meterReading.create({
    data: { meterId: bareMeter, readingStart: '50', readingEnd: '90', periodStart: new Date('2020-02-01'), periodEnd: new Date('2020-02-29'), status: 'PENDING', submittedByUserId: 'zz-tpp-tenant' },
  });
  await api.confirmReading({ id: declared.id });
  const confirmed = await prisma.meterReading.findUniqueOrThrow({ where: { id: declared.id }, select: { status: true, grossAmount: true } });
  ck('E4 it is confirmed', confirmed.status === 'CONFIRMED', `got ${confirmed.status}`);
  ck('E5 but stays unpriced', confirmed.grossAmount === null, `got ${confirmed.grossAmount}`);
  ck('E6 and is reported as waiting for a rate', (await blockOf(orgId, declared.id)) === 'NO_TARIFF', `got ${await blockOf(orgId, declared.id)}`);
  await api.upsertTariff({ chargeTypeId: water.id, propertyId: bare.id, unitRate: '4', fixedCharge: '1' });
  ck('E7 setting the rate prices it (40 × 4 + 1)', (await grossOf(declared.id)) === '161.00', `got ${await grossOf(declared.id)}`);
  ck('E8 without re-pricing the reading priced under the old rate', (await grossOf(pricedEarlier)) === '30.00', `got ${await grossOf(pricedEarlier)}`);

  console.log('\nF. A meter spanning two properties has no rate until its units are put right');
  // Only data from before the rule can look like this — createMeter refuses it (G1).
  const legacy = await prisma.meter.create({ data: { chargeTypeId: water.id, serialNo: `${SERIAL}LEGACY`, units: { create: [{ unitId: h3.id }, { unitId: k2.id }] } } });
  const legacyRead = await read(legacy.id, '2019-12-01', '2019-12-31', '0', '10');
  ck('F1 its reading is unpriced', (await grossOf(legacyRead)) === null, `got ${await grossOf(legacyRead)}`);
  // Not "this property has no rate": both properties have one, and setting
  // either would not help.
  ck('F2 and reported as spanning properties, not as a missing rate', (await blockOf(orgId, legacyRead)) === 'METER_SPANS_PROPERTIES', `got ${await blockOf(orgId, legacyRead)}`);
  ck('F3 the meter list shows it in no property', (await api.meters()).find((m) => m.id === legacy.id)?.propertyId === null);
  await api.updateMeter({ id: legacy.id, unitIds: [k2.id] });
  ck('F4 once it covers one property, the waiting reading is priced at that rate (10 × 5)', (await grossOf(legacyRead)) === '50.00', `got ${await grossOf(legacyRead)}`);

  console.log('\nG. A meter and the meters deducted from it stay in one property');
  const sameProperty = 'A sub-meter must be in the same property as its master';
  const g1 = await refused(() => api.createMeter({ chargeTypeId: water.id, serialNo: `${SERIAL}SPLIT`, unitIds: [h3.id, k2.id] }));
  ck('G1 a new meter over two properties is refused', g1 === 'All units on a meter must be in the same property', g1);
  const spare = await mkMeter('H-SPARE', [h3.id]);
  const g2 = await refused(() => api.createMeter({ chargeTypeId: water.id, serialNo: `${SERIAL}K-MASTER`, unitIds: [k2.id], subMeterIds: [spare] }));
  ck('G2 a sub-meter in another property is refused', g2 === sameProperty, g2);
  const g3 = await refused(() => api.updateMeter({ id: hillMeter, subMeterIds: [spare] }));
  ck('G3 on an existing master as well', g3 === sameProperty, g3);
  const g4 = await refused(() => api.updateMeter({ id: master, unitIds: [k2.id] }));
  ck('G4 a master cannot move away from its sub-meters', g4 === sameProperty, g4);
  const g5 = await refused(() => api.updateMeter({ id: sub, unitIds: [k2.id] }));
  ck('G5 nor a sub-meter away from its master', g5 === sameProperty, g5);
  const unmoved = await prisma.meterUnit.findMany({ where: { meterId: { in: [master, sub] } }, select: { unitId: true } });
  ck('G6 and a refused move changes nothing', unmoved.length === 2 && unmoved.some((u) => u.unitId === h1.id) && unmoved.some((u) => u.unitId === h2.id));
  const g7 = await refused(() => api.updateMeter({ id: master, unitIds: [h1.id, h3.id] }));
  ck('G7 moving within the property is allowed', g7 === '', g7);

  console.log('\nH. A rate is only for this organisation’s utilities and live properties');
  const h1r = await refused(() => api.upsertTariff({ chargeTypeId: water.id, propertyId: otherProperty.id, unitRate: '1' }));
  ck('H1 another organisation’s property is refused', h1r === 'Property not found', h1r);
  const h2r = await refused(() => api.upsertTariff({ chargeTypeId: rentCt.id, propertyId: harbour.id, unitRate: '1' }));
  ck('H2 a charge type that is not a utility is refused', h2r === 'Utility charge type not found', h2r);
  const h3r = await refused(() => api.upsertTariff({ chargeTypeId: otherWater.id, propertyId: harbour.id, unitRate: '1' }));
  ck('H3 another organisation’s utility is refused', h3r === 'Utility charge type not found', h3r);
  const h4r = await refused(() => api.upsertTariff({ chargeTypeId: water.id, propertyId: gone.id, unitRate: '1' }));
  ck('H4 an archived property is refused', h4r === 'Property not found', h4r);
  const h5r = await refused(() => api.deleteTariff({ chargeTypeId: water.id, propertyId: otherProperty.id }));
  ck('H5 nor can a rate be cleared across organisations', h5r === 'Property not found', h5r);
  const stray = await prisma.utilityTariff.count({
    where: { OR: [{ propertyId: { in: [otherProperty.id, gone.id] } }, { chargeTypeId: { in: [rentCt.id, otherWater.id] }, propertyId: harbour.id }] },
  });
  ck('H6 none of them wrote a rate', stray === 0, `found ${stray}`);

  console.log('\nI. Meters from before the one-property rule stay editable, and a master across two properties waits');
  // Only data from before the rule can look like this, so it is written directly.
  const oldMaster = await prisma.meter.create({ data: { chargeTypeId: water.id, serialNo: `${SERIAL}OLD-M`, units: { create: [{ unitId: k1.id }] } } });
  const oldSub = await prisma.meter.create({ data: { chargeTypeId: water.id, serialNo: `${SERIAL}OLD-S`, parentMeterId: oldMaster.id, units: { create: [{ unitId: h3.id }] } } });
  const oldMixed = await prisma.meter.create({ data: { chargeTypeId: water.id, serialNo: `${SERIAL}OLD-X`, units: { create: [{ unitId: h3.id }, { unitId: k2.id }] } } });
  // What the edit dialog sends: every field, units and sub-meters as they are.
  const i1 = await refused(() => api.updateMeter({ id: oldMixed.id, serialNo: `${SERIAL}OLD-X`, isActive: false, unitIds: [k2.id, h3.id], subMeterIds: [] }));
  const mixedNow = await prisma.meter.findUniqueOrThrow({ where: { id: oldMixed.id }, select: { isActive: true } });
  ck('I1 a meter over two properties can still be switched off', i1 === '' && !mixedNow.isActive, i1 || `active ${mixedNow.isActive}`);
  const i2 = await refused(() => api.updateMeter({ id: oldMaster.id, serialNo: `${SERIAL}OLD-M`, isActive: true, unitIds: [k1.id], subMeterIds: [oldSub.id] }));
  ck('I2 so can a master with a sub-meter in another property', i2 === '', i2);
  const i3 = await refused(() => api.updateMeter({ id: oldSub.id, serialNo: `${SERIAL}OLD-S`, isActive: true, unitIds: [h3.id], subMeterIds: [] }));
  ck('I3 and that sub-meter', i3 === '', i3);
  const i4 = await refused(() => api.updateMeter({ id: oldMixed.id, unitIds: [k2.id, h2.id] }));
  ck('I4 but actually changing its units is still held to the rule', i4 === 'All units on a meter must be in the same property', i4);
  const oldMasterRead = await read(oldMaster.id, '2020-02-01', '2020-02-29', '0', '100');
  await read(oldSub.id, '2020-02-01', '2020-02-29', '0', '30');
  // Re-priced at Hill's 5, the 30 taken off would be charged again at Harbour's 2.
  ck('I5 the master’s reading waits for the pair to be in one property', (await blockOf(orgId, oldMasterRead)) === 'METER_SPANS_PROPERTIES', `got ${await blockOf(orgId, oldMasterRead)}`);
  const hillLater = await meteredLines(await draft(leaseHill.id, '2020-03'));
  ck('I6 and is not billed at two properties’ rates', hillLater.length === 0 && (await billedOn(oldMasterRead)) === null, `got ${hillLater.map((l) => l.amount)}`);
  await api.updateMeter({ id: oldMaster.id, subMeterIds: [] });
  ck('I7 once the sub-meter is detached nothing holds it back', (await blockOf(orgId, oldMasterRead)) === undefined, `got ${await blockOf(orgId, oldMasterRead)}`);

  console.log('\nJ. A rate saved at the same moment as a reading still prices it');
  const late = await mkProperty('Late', ['L1']);
  const lateMeter = await mkMeter('L-1', [late.units[0].id]);
  // A MeteringService whose next `misses` rate lookups find nothing: the rate
  // was committed just after it looked.
  const rateCommitsLate = (misses: number) =>
    new MeteringService({
      meter: prisma.meter,
      meterReading: prisma.meterReading,
      utilityTariff: { findMany: (args: Prisma.UtilityTariffFindManyArgs) => (misses-- > 0 ? Promise.resolve([]) : prisma.utilityTariff.findMany(args)) },
    } as unknown as PrismaService);

  // Confirming prices the declaration while it is still awaiting review, finding
  // no rate; the rate is saved before it is marked confirmed, so the rate's own
  // sweep skips it as unconfirmed.
  const lateDeclared = await prisma.meterReading.create({
    data: { meterId: lateMeter, readingStart: '0', readingEnd: '25', periodStart: new Date('2020-02-01'), periodEnd: new Date('2020-02-29'), status: 'PENDING', submittedByUserId: 'zz-tpp-tenant' },
  });
  const rateMidConfirm: MeteringService = Object.assign(Object.create(metering) as MeteringService, {
    updateReading: async (input: Parameters<MeteringService['updateReading']>[0]) => {
      const row = await metering.updateReading(input);
      await metering.setTariff({ organizationId: orgId, chargeTypeId: water.id, propertyId: late.id, unitRate: '2', fixedCharge: '0' });
      return row;
    },
  });
  await meteringRouter.createCaller({ ...staffCtx(orgId), metering: rateMidConfirm } as unknown as Context).confirmReading({ id: lateDeclared.id });
  ck('J1 a declaration confirmed while its rate is saved is priced (25 × 2)', (await grossOf(lateDeclared.id)) === '50.00', `got ${await grossOf(lateDeclared.id)}`);
  const lateRead = await rateCommitsLate(1).createReading({ organizationId: orgId, meterId: lateMeter, readingStart: '25', readingEnd: '40', periodStart: '2020-03-01', periodEnd: '2020-03-31' });
  ck('J2 so is a reading recorded while it is saved (15 × 2)', lateRead.grossAmount?.toFixed(2) === '30.00' && (await grossOf(lateRead.id)) === '30.00', `got ${lateRead.grossAmount} / ${await grossOf(lateRead.id)}`);
  const lateFixed = await rateCommitsLate(1).updateReading({ organizationId: orgId, id: lateRead.id, readingStart: '25', readingEnd: '45', periodStart: '2020-03-01', periodEnd: '2020-03-31' });
  ck('J3 and one corrected while it is saved (20 × 2)', lateFixed.grossAmount?.toFixed(2) === '40.00' && (await grossOf(lateRead.id)) === '40.00', `got ${lateFixed.grossAmount} / ${await grossOf(lateRead.id)}`);

  // The rate's sweep has read 0 → 100 and is about to write its amount when a
  // correction to 0 → 50 lands — made by someone who could not see the rate yet,
  // so it too leaves the reading unpriced.
  const later = await mkProperty('Later', ['M1']);
  const laterMeter = await mkMeter('M-1', [later.units[0].id]);
  const laterRead = await read(laterMeter, '2020-02-01', '2020-02-29', '0', '100');
  let correctedMidSweep = false;
  await new MeteringService({
    chargeType: prisma.chargeType,
    property: prisma.property,
    meterReading: prisma.meterReading,
    utilityTariff: {
      upsert: (args: Prisma.UtilityTariffUpsertArgs) => prisma.utilityTariff.upsert(args),
      findMany: async (args: Prisma.UtilityTariffFindManyArgs) => {
        if (!correctedMidSweep) {
          correctedMidSweep = true;
          await prisma.meterReading.update({ where: { id: laterRead }, data: { readingEnd: '50' } });
        }
        return prisma.utilityTariff.findMany(args);
      },
    },
  } as unknown as PrismaService).setTariff({ organizationId: orgId, chargeTypeId: water.id, propertyId: later.id, unitRate: '2', fixedCharge: '0' });
  ck('J4 a reading corrected mid-sweep is not priced at the usage it no longer has (not 100 × 2)', correctedMidSweep && (await grossOf(laterRead)) === null, `got ${await grossOf(laterRead)}`);
  await metering.priceUnpriced({ id: laterMeter });
  ck('J5 the correction’s own second look prices what it now reads (50 × 2)', (await grossOf(laterRead)) === '100.00', `got ${await grossOf(laterRead)}`);
}

async function purgeStale() {
  const meters = await prisma.meter.findMany({ where: { serialNo: { startsWith: SERIAL } }, select: { id: true } });
  const ids = meters.map((m) => m.id);
  if (ids.length) {
    await prisma.meterReading.deleteMany({ where: { meterId: { in: ids } } });
    await prisma.meter.updateMany({ where: { id: { in: ids } }, data: { parentMeterId: null } });
    await prisma.meterUnit.deleteMany({ where: { meterId: { in: ids } } });
    await prisma.meter.deleteMany({ where: { id: { in: ids } } });
  }
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: REF } }, select: { id: true } });
  for (const l of leases) {
    const invIds = (await prisma.invoice.findMany({ where: { leaseId: l.id }, select: { id: true } })).map((i) => i.id);
    if (invIds.length) {
      const entries = await prisma.journalEntry.findMany({ where: { OR: [{ sourceId: { in: invIds } }, { lines: { some: { invoiceId: { in: invIds } } } }] }, select: { id: true } });
      const eids = entries.map((e) => e.id);
      if (eids.length) {
        await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } });
        await prisma.journalEntry.deleteMany({ where: { id: { in: eids } } });
      }
      await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invIds } } });
      await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
    }
    await prisma.leaseUnit.deleteMany({ where: { leaseId: l.id } });
    await prisma.chargeRule.deleteMany({ where: { leaseId: l.id } });
    await prisma.lease.delete({ where: { id: l.id } }).catch(() => {});
  }
  // A property's rates go with it.
  const props = await prisma.property.findMany({ where: { name: { startsWith: `${PROP} ` } }, select: { id: true, units: { select: { id: true } } } });
  for (const p of props) {
    await prisma.unit.deleteMany({ where: { id: { in: p.units.map((u) => u.id) } } });
    await prisma.property.delete({ where: { id: p.id } }).catch(() => {});
  }
  await prisma.tenant.deleteMany({ where: { name: TENANT } });
  await prisma.chargeType.deleteMany({ where: { code: { in: [CT_CODE, OTHER_CT_CODE] } } });
  await prisma.organization.deleteMany({ where: { code: OTHER_ORG } });
}

async function cleanup() {
  try { await purgeStale(); console.log('\nCleanup: OK'); }
  catch (e) { console.log(`\nCleanup WARNING: ${e instanceof Error ? e.message : e}`); }
}

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