/**
 * Functional smoke: Deposit Receipts — money a tenant paid for a lease before
 * its debit note existed, or over what a note owed.
 *
 * The office books two kinds of payment: a Receipt against a note already
 * issued, and a Deposit Receipt for money that arrives first. The second had
 * nowhere to go — a receipt had to name an issued note and could not exceed it.
 * The owner's choices: a deposit receipt belongs to one lease and pays only that
 * lease's notes; it is drawn automatically, as each note is issued; and paying
 * more than a note owes books the rest as a deposit receipt of its own —
 * whether the office records it or the tenant states it from the portal.
 *
 * What has to hold, and is asserted: the money sits in Tenant Credit (2350),
 * not in AR and not in Deposits Held; the oldest deposit receipt is used first;
 * one lease's credit never pays another's note; a drawing can be withdrawn,
 * which is what voiding a note paid this way needs; a bounce takes back every
 * drawing; two things done at once on one lease spend its credit once; and the
 * ledger's credit for a lease always equals what its deposit receipts have left.
 * And every payment waiting on the office is in My Approvals and counted in the
 * sidebar for whoever may approve it — the overpaid part only with its receipt.
 *
 * Runs in its own organisation. Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/deposit-receipt-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import type { Prisma } from '@prisma/client';
import { Decimal } from '@rms/domain';
import { ApprovalService } from '../src/approvals/approval.service';
import { invoiceArState } from '../src/billing/invoice-ar';
import { BillingService } from '../src/billing/billing.service';
import { NumberService } from '../src/common/number.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { leaseCredit, remainingOf } from '../src/payments/lease-credit';
import { PaymentsService } from '../src/payments/payments.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { ReportsService } from '../src/reports/reports.service';
import { approvalsRouter } from '../src/trpc/routers/approvals.router';
import { receiptsRouter } from '../src/trpc/routers/receipts.router';
import type { AuthUser } from '../src/trpc/auth-user';
import type { Context } from '../src/trpc/trpc';

const prisma = new PrismaService();
const ledger = new LedgerService();
const numbers = new NumberService();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, ledger, numbers, new EventEmitter2(), approvals);
const payments = new PaymentsService(prisma, ledger, numbers, new EventEmitter2());
const reports = new ReportsService(prisma);
const tx = prisma as unknown as Prisma.TransactionClient;

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 ORG_CODE = 'ZZ-DRC-ORG';
const TENANT_LOGIN = 'zz-drc-tenant@rms.local';

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'ZZ Deposit receipt smoke org' } })).id;
  for (const [docType, prefix] of [['INVOICE', 'ZDN-'], ['RECEIPT', 'ZRE-'], ['DEPOSIT_RECEIPT', 'ZDR-'], ['DEPOSIT', 'ZDEP-'], ['LEASE', 'ZL-']]) {
    await prisma.numberSequence.create({ data: { organizationId: orgId, docType, prefix, padding: 6 } });
  }
  const gl: Record<string, string> = {};
  for (const [code, name, type, role] of [['1000', 'Bank', 'ASSET', 'BANK'], ['1100', 'AR', 'ASSET', 'RECEIVABLE'], ['2300', 'Deposits Held', 'LIABILITY', 'DEPOSITS_HELD'], ['2350', 'Tenant Credit', 'LIABILITY', 'TENANT_CREDIT'], ['4000', 'Rental Income', 'INCOME', null]] as const) {
    gl[code] = (await prisma.glAccount.create({ data: { organizationId: orgId, code, name, type, role } })).id;
  }
  const balance = async (code: string) => {
    const lines = await prisma.journalLine.findMany({ where: { accountId: gl[code] }, select: { direction: true, amount: true } });
    // Liabilities read credit-positive, assets debit-positive.
    const sign = code.startsWith('2') ? -1 : 1;
    return lines.reduce((a, l) => a.plus(new Decimal(l.amount.toString()).times(l.direction === 'DEBIT' ? sign : -sign)), new Decimal(0)).toFixed(2);
  };
  const rent = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'RENT', nameEn: 'Rent', category: 'RECURRING', glAccountId: gl['4000'] } });
  const depCt = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'RENT_DEPOSIT', nameEn: 'Rent Deposit', category: 'DEPOSIT', glAccountId: gl['2300'] } });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Credit Tenant' } });
  const stranger = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Stranger' } });
  const property = await prisma.property.create({ data: { organizationId: orgId, name: 'ZZ Credit Property', units: { create: [{ name: 'A' }, { name: 'B' }, { name: 'C' }, { name: 'D' }, { name: 'E' }, { name: 'F' }] } }, include: { units: true } });
  const mkLease = (ref: string, unit: number, monthly: string, opts: { status?: 'ACTIVE' | 'ENDED'; tenantId?: string; deposit?: string } = {}) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `ZZ-DRC-${ref}`, tenantId: opts.tenantId ?? tenant.id, status: opts.status ?? 'ACTIVE', currency: 'HKD',
        startDate: new Date('2020-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0, units: { create: [{ unitId: property.units[unit].id }] },
        chargeRules: { create: [
          { chargeTypeId: rent.id, amount: monthly, frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 },
          ...(opts.deposit ? [{ chargeTypeId: depCt.id, amount: opts.deposit, frequencyMonths: 0, timing: 'ADVANCE' as const, proration: 'FULL_MONTH' as const, firstInvoiceOnly: true, sortOrder: 1 }] : []),
        ] },
      },
    });
  const L1 = await mkLease('L1', 0, '1000');
  const L2 = await mkLease('L2', 1, '500');
  const ended = await mkLease('OLD', 2, '800', { status: 'ENDED' });
  const theirs = await mkLease('THEIRS', 3, '900', { tenantId: stranger.id });

  const periodOf = new Map<string, number>();
  const issueNext = async (leaseId: string) => {
    const n = (periodOf.get(leaseId) ?? 0) + 1;
    periodOf.set(leaseId, n);
    const draft = await billing.generateDraft({ organizationId: orgId, leaseId, period: `2020-${String(n).padStart(2, '0')}` });
    return billing.issue({ organizationId: orgId, invoiceId: draft.id });
  };
  const statusOf = async (id: string) => (await prisma.invoice.findUniqueOrThrow({ where: { id }, select: { status: true } })).status;
  const owed = async (id: string) => (await invoiceArState(tx, orgId, id)).outstanding.toFixed(2);
  const credit = async (leaseId: string) => (await leaseCredit(tx, orgId, leaseId)).toFixed(2);
  const record = (leaseId: string, amount: string, receivedDate?: string) =>
    payments.recordDepositReceipt({ organizationId: orgId, tenantId: tenant.id, leaseId, amount, receivedDate: receivedDate ? new Date(receivedDate) : undefined });
  const approve = (receiptId: string) => payments.approve({ organizationId: orgId, receiptId });

  console.log('A. Money for a lease before its note exists');
  const dr1 = await record(L1.id, '3000', '2019-12-20');
  ck('A1 recorded as a pending deposit receipt with its own number', dr1.kind === 'DEPOSIT_RECEIPT' && dr1.status === 'PENDING' && dr1.number.startsWith('ZDR-'), `got ${dr1.kind} ${dr1.status} ${dr1.number}`);
  ck('A2 pending, it holds nothing yet', (await credit(L1.id)) === '0.00');
  await approve(dr1.id);
  ck('A3 approved, the lease holds it', (await credit(L1.id)) === '3000.00', `got ${await credit(L1.id)}`);
  ck('A4 in Tenant Credit, banked — not AR, not Deposits Held', (await balance('2350')) === '3000.00' && (await balance('1000')) === '3000.00' && (await balance('1100')) === '0.00' && (await balance('2300')) === '0.00');
  ck('A5 refused for another tenant’s lease', (await refused(() => record(theirs.id, '100'))).includes('current or upcoming lease'));
  ck('A6 refused for an ended lease', (await refused(() => record(ended.id, '100'))).includes('current or upcoming lease'));
  ck('A7 refused for nothing', (await refused(() => record(L1.id, '0'))).includes('positive'));

  console.log('\nB. Drawn onto the lease’s notes as they are issued');
  const jan = await issueNext(L1.id);
  ck('B1 the first note goes out already paid', jan.status === 'PAID' && (await owed(jan.id)) === '0.00', `got ${jan.status} ${await owed(jan.id)}`);
  ck('B2 the lease holds the rest', (await credit(L1.id)) === '2000.00', `got ${await credit(L1.id)}`);
  const janPaidBy = await prisma.receiptAllocationItem.findMany({ where: { invoiceId: jan.id }, include: { allocation: { include: { receipt: true } } } });
  ck('B3 and the note says which deposit receipt paid it', janPaidBy.length === 1 && janPaidBy[0].allocation.receipt.number === dr1.number);
  const l2jan = await issueNext(L2.id);
  ck('B4 another lease’s note is not paid from it', l2jan.status === 'ISSUED' && (await credit(L1.id)) === '2000.00', `got ${l2jan.status}`);
  const feb = await issueNext(L1.id);
  const mar = await issueNext(L1.id);
  const apr = await issueNext(L1.id);
  ck('B5 two more paid, the fourth goes out owing — the credit ran out', feb.status === 'PAID' && mar.status === 'PAID' && apr.status === 'ISSUED' && (await credit(L1.id)) === '0.00', `got ${feb.status} ${mar.status} ${apr.status} ${await credit(L1.id)}`);
  const dr2 = await record(L1.id, '300');
  await approve(dr2.id);
  ck('B6 a deposit receipt approved while a note is open pays it at once', (await statusOf(apr.id)) === 'PARTIALLY_PAID' && (await owed(apr.id)) === '700.00', `got ${await statusOf(apr.id)} ${await owed(apr.id)}`);

  console.log('\nC. The oldest deposit receipt is used first');
  const older = await record(L2.id, '200', '2020-01-02');
  const newer = await record(L2.id, '400', '2020-01-05');
  await approve(newer.id);
  await approve(older.id);
  const remainOf = async (id: string) => remainingOf(await prisma.receipt.findUniqueOrThrow({ where: { id }, include: { allocations: { include: { items: true } } } })).toFixed(2);
  ck('C1 L2’s open note is paid off', (await statusOf(l2jan.id)) === 'PAID', `got ${await statusOf(l2jan.id)}`);
  // newer was approved first and drew 400 onto the 500 note; older then drew the last 100.
  ck('C2 each drawn as it arrived, the later one wholly', (await remainOf(newer.id)) === '0.00' && (await remainOf(older.id)) === '100.00', `got newer ${await remainOf(newer.id)} older ${await remainOf(older.id)}`);
  const l2feb = await issueNext(L2.id);
  ck('C3 the next note draws the older one’s remainder first', (await remainOf(older.id)) === '0.00' && (await owed(l2feb.id)) === '400.00', `got older ${await remainOf(older.id)} owed ${await owed(l2feb.id)}`);

  console.log('\nD. Paying more than a note owes');
  const pay = await payments.recordBulkPayment({
    organizationId: orgId, tenantId: tenant.id, amount: '700', allocations: [{ invoiceId: apr.id, amount: '700' }],
    overpayment: { amount: '500', leaseId: L1.id },
  });
  const extra = await prisma.receipt.findFirstOrThrow({ where: { sourceReceiptId: pay.id } });
  ck('D1 the rest is booked as a deposit receipt of its own, tied to the receipt', extra.kind === 'DEPOSIT_RECEIPT' && extra.amount.toFixed(2) === '500.00' && extra.leaseId === L1.id && extra.status === 'PENDING');
  ck('D2 it cannot be approved apart from its receipt', (await refused(() => approve(extra.id))).includes('approve that receipt instead'));
  await approve(pay.id);
  ck('D3 approving the receipt approves both', (await prisma.receipt.findUniqueOrThrow({ where: { id: extra.id } })).status === 'APPROVED' && (await statusOf(apr.id)) === 'PAID');
  ck('D4 and the lease holds the overpaid part', (await credit(L1.id)) === '500.00', `got ${await credit(L1.id)}`);
  const may = await issueNext(L1.id);
  ck('D5 which pays half the next note', (await statusOf(may.id)) === 'PARTIALLY_PAID' && (await owed(may.id)) === '500.00', `got ${await statusOf(may.id)} ${await owed(may.id)}`);
  const toRefuse = await payments.recordBulkPayment({
    organizationId: orgId, tenantId: tenant.id, amount: '500', allocations: [{ invoiceId: may.id, amount: '500' }], overpayment: { amount: '50', leaseId: L1.id },
  });
  await payments.reject({ organizationId: orgId, receiptId: toRefuse.id, reason: 'ZZ wrong amount' });
  ck('D6 refusing the receipt refuses its overpaid part', (await prisma.receipt.findFirstOrThrow({ where: { sourceReceiptId: toRefuse.id } })).status === 'REJECTED');
  ck('D7 an overpayment for another tenant’s lease is refused', (await refused(() => payments.recordBulkPayment({
    organizationId: orgId, tenantId: tenant.id, amount: '10', allocations: [{ invoiceId: may.id, amount: '10' }], overpayment: { amount: '5', leaseId: theirs.id },
  }))).includes('current or upcoming lease'));
  // The tenant's own declaration from the portal: what they banked, not what was owed.
  const told = await payments.submitReceipt({ organizationId: orgId, tenantId: tenant.id, invoiceId: l2feb.id, amount: '450', reference: 'ZZ-TT-1' });
  const toldExtra = await prisma.receipt.findFirst({ where: { sourceReceiptId: told.id } });
  ck('D8 a tenant stating 450 on a note owing 400: the note takes 400, the 50 is held for its lease',
    told.amount.toFixed(2) === '400.00' && toldExtra?.amount.toFixed(2) === '50.00' && toldExtra.leaseId === L2.id && toldExtra.status === 'PENDING' && toldExtra.reference === 'ZZ-TT-1',
    `got ${told.amount} + ${toldExtra?.amount} for ${toldExtra?.leaseId}`);
  await approve(told.id);
  ck('D9 approved once: the note is paid and the lease holds the 50', (await statusOf(l2feb.id)) === 'PAID' && (await credit(L2.id)) === '50.00', `got ${await statusOf(l2feb.id)} ${await credit(L2.id)}`);
  const L6 = await mkLease('L6', 3, '800');
  const last = await issueNext(L6.id);
  await prisma.lease.update({ where: { id: L6.id }, data: { status: 'ENDED' } });
  const submit = (amount: string) => payments.submitReceipt({ organizationId: orgId, tenantId: tenant.id, invoiceId: last.id, amount });
  ck('D10 a lease that has ended holds nothing: the tenant cannot pay over what is owed', (await refused(() => submit('900'))).includes('This lease has ended'));
  const exact = await submit('800');
  ck('D11 but can still pay what is owed', exact.amount.toFixed(2) === '800.00' && !(await prisma.receipt.findFirst({ where: { sourceReceiptId: exact.id } })));

  console.log('\nE. A note paid from credit is voided by withdrawing the drawing first');
  const voidFirst = await refused(() => billing.voidInvoice({ organizationId: orgId, invoiceId: jan.id }));
  // Refused for being paid, before the AR check is even reached.
  ck('E1 voiding it straight away is refused', voidFirst.includes('Reverse the payments first'), `got "${voidFirst}"`);
  const before = await credit(L1.id);
  await payments.withdrawCredit({ organizationId: orgId, allocationId: janPaidBy[0].allocationId });
  ck('E2 withdrawn, the note owes again and the lease has the money back', (await statusOf(jan.id)) === 'ISSUED' && (await credit(L1.id)) === new Decimal(before).plus(1000).toFixed(2), `got ${await statusOf(jan.id)} ${await credit(L1.id)}`);
  ck('E3 now it can be voided', (await billing.voidInvoice({ organizationId: orgId, invoiceId: jan.id })).status === 'VOID');
  ck('E4 withdrawing the same drawing twice is refused', (await refused(() => payments.withdrawCredit({ organizationId: orgId, allocationId: janPaidBy[0].allocationId }))).includes('already been withdrawn'));
  const jun = await issueNext(L1.id);
  ck('E5 the returned credit pays the next note issued', jun.status === 'PAID' && (await statusOf(may.id)) === 'PARTIALLY_PAID', `got ${jun.status}`);

  console.log('\nF. A bounce takes back every drawing');
  const L3 = await mkLease('L3', 2, '600', { deposit: '1200' });
  const dr3 = await record(L3.id, '2000');
  await approve(dr3.id);
  const first = await issueNext(L3.id);
  ck('F1 a first note with a deposit charge, paid in full from credit', first.status === 'PAID' && (await owed(first.id)) === '0.00', `got ${first.status}`);
  const managed = await prisma.deposit.findFirst({ where: { sourceInvoiceId: first.id } });
  ck('F2 raises the security deposit, as a paid receipt would', managed?.status === 'HELD' && managed.amount.toFixed(2) === '1200.00', `got ${JSON.stringify(managed && { s: managed.status, a: managed.amount })}`);
  await payments.bounce({ organizationId: orgId, receiptId: dr3.id, reason: 'ZZ bounced' });
  ck('F3 the note is owed again in full', (await statusOf(first.id)) === 'ISSUED' && (await owed(first.id)) === '1800.00', `got ${await statusOf(first.id)} ${await owed(first.id)}`);
  ck('F4 the security deposit that payment raised is void', (await prisma.deposit.findUniqueOrThrow({ where: { id: managed!.id } })).status === 'VOID');
  ck('F5 and the lease holds nothing from it', (await credit(L3.id)) === '0.00', `got ${await credit(L3.id)}`);
  const extraBounce = await refused(() => payments.bounce({ organizationId: orgId, receiptId: extra.id }));
  ck('F6 an overpaid part cannot be bounced apart from its receipt', extraBounce.includes('bounce that receipt instead'));
  await payments.bounce({ organizationId: orgId, receiptId: pay.id });
  const extraNow = await prisma.receipt.findUniqueOrThrow({ where: { id: extra.id }, include: { allocations: true } });
  ck('F7 bouncing the receipt bounces its overpaid part and takes back its drawings', extraNow.status === 'BOUNCED' && extraNow.allocations.every((a) => a.status === 'VOID'), `got ${extraNow.status}`);

  console.log('\nG. Two things at once on one lease');
  // Each side reads the lease's credit and spends it; unless they queue, both
  // spend the same money, or each misses what the other did.
  const L4 = await mkLease('L4', 4, '1000');
  await approve((await record(L4.id, '1000')).id);
  const twin = [
    await billing.generateDraft({ organizationId: orgId, leaseId: L4.id, period: '2020-01' }),
    await billing.generateDraft({ organizationId: orgId, leaseId: L4.id, period: '2020-02' }),
  ];
  await Promise.all(twin.map((d) => billing.issue({ organizationId: orgId, invoiceId: d.id })));
  const twinStatus = (await Promise.all(twin.map((d) => statusOf(d.id)))).sort().join(' ');
  ck('G1 two notes issued together: the credit pays one, the other is owed', twinStatus === 'ISSUED PAID' && (await credit(L4.id)) === '0.00', `got ${twinStatus}, credit ${await credit(L4.id)}`);
  const L5 = await mkLease('L5', 5, '1000');
  const early = await record(L5.id, '600');
  const meanwhile = await billing.generateDraft({ organizationId: orgId, leaseId: L5.id, period: '2020-01' });
  await Promise.all([approve(early.id), billing.issue({ organizationId: orgId, invoiceId: meanwhile.id })]);
  ck('G2 a deposit receipt approved as a note is issued pays it, not left unused', (await owed(meanwhile.id)) === '400.00' && (await credit(L5.id)) === '0.00', `got owed ${await owed(meanwhile.id)}, credit ${await credit(L5.id)}`);

  console.log('\nH. The books agree');
  for (const lease of [L1, L2, L3, L4, L5]) {
    const drs = await prisma.receipt.findMany({ where: { leaseId: lease.id, kind: 'DEPOSIT_RECEIPT', status: 'APPROVED' }, include: { allocations: { include: { items: true } } } });
    const left = drs.reduce((a, r) => a.plus(remainingOf(r)), new Decimal(0)).toFixed(2);
    ck(`H1 ${lease.reference}: the ledger’s credit equals what its deposit receipts have left`, (await credit(lease.id)) === left, `ledger ${await credit(lease.id)} receipts ${left}`);
  }
  const lines = await prisma.journalLine.findMany({ where: { entry: { organizationId: orgId } }, select: { direction: true, amount: true } });
  const net = lines.reduce((a, l) => (l.direction === 'DEBIT' ? a.plus(l.amount.toString()) : a.minus(l.amount.toString())), new Decimal(0));
  ck('H2 every entry balances', net.isZero(), `net ${net.toFixed(2)}`);
  const cash = await reports.collections(orgId, '2019-01-01', '2100-01-01');
  const banked = await balance('1000');
  const collected = cash.groups.find((g) => g.currency === 'HKD');
  ck('H3 the collections report counts deposit receipts as money in', collected !== undefined && Number(collected.total) >= Number(banked), `report ${collected?.total} bank ${banked}`);

  console.log('\nI. Waiting on the office: My Approvals and the sidebar');
  // Still pending from D11: the payment on the lease that has ended.
  const reviewer: AuthUser = {
    id: 'zz-drc-reviewer', email: 'zz-drc-reviewer@rms.local', name: 'ZZ Reviewer', tenantId: null, mustChangePassword: false,
    roles: [], permissions: ['receipt.read', 'receipt.update'],
  };
  const reader: AuthUser = { ...reviewer, id: 'zz-drc-reader', permissions: ['receipt.read'] };
  const ctxOf = (user: AuthUser) => ({ prisma, user, organizationId: orgId, approvals, payments } as unknown as Context);
  const office = receiptsRouter.createCaller(ctxOf(reviewer));
  const badges = async (user = reviewer) => JSON.stringify(await approvalsRouter.createCaller(ctxOf(user)).badges());
  const login = await prisma.user.create({ data: { email: TENANT_LOGIN, passwordHash: 'x', name: 'ZZ Credit Tenant login', tenantId: tenant.id } });
  const L7 = await mkLease('L7', 0, '300');
  const owing = await issueNext(L7.id);
  const owingNo = (await prisma.invoice.findUniqueOrThrow({ where: { id: owing.id }, select: { number: true } })).number;
  const sent = await payments.submitReceipt({ organizationId: orgId, tenantId: tenant.id, invoiceId: owing.id, amount: '350', uploadedByUserId: login.id });
  const sentExtra = await prisma.receipt.findFirstOrThrow({ where: { sourceReceiptId: sent.id } });
  const advance = await record(L7.id, '100');
  const listed = await office.pending();
  const row = (id: string) => listed.find((r) => r.id === id);
  const sentRow = row(sent.id);
  ck('I1 a payment the tenant sent is listed as theirs, with the note it pays and its overpaid part',
    sentRow?.fromTenant === true && sentRow.kind === 'RECEIPT' && Number(sentRow.amount) === 300 && sentRow.invoices.join() === owingNo
      && sentRow.overpaid.length === 1 && sentRow.overpaid[0].number === sentExtra.number && Number(sentRow.overpaid[0].amount) === 50,
    JSON.stringify(sentRow));
  const advanceRow = row(advance.id);
  ck('I2 one the office recorded is listed too, not as the tenant’s',
    advanceRow?.fromTenant === false && advanceRow.kind === 'DEPOSIT_RECEIPT' && advanceRow.leaseReference === 'ZZ-DRC-L7', JSON.stringify(advanceRow));
  ck('I3 the overpaid part is not listed apart from its receipt', !row(sentExtra.id));
  ck('I4 nothing approved or refused is listed; the oldest comes first',
    listed.map((r) => r.id).join() === [exact.id, sent.id, advance.id].join(), `got ${listed.map((r) => r.number).join(', ')}`);
  ck('I5 the sidebar counts them by page, and all of them in My Approvals',
    (await badges()) === JSON.stringify({ myApprovals: 3, receipts: 2, depositReceipts: 1 }), await badges());
  ck('I6 someone who cannot approve them has nothing counted',
    (await badges(reader)) === JSON.stringify({ myApprovals: 0, receipts: 0, depositReceipts: 0 }), await badges(reader));
  ck('I7 and is not shown them', (await refused(() => receiptsRouter.createCaller(ctxOf(reader)).pending())).includes('Missing permission'));
  await office.approve({ receiptId: sent.id });
  await office.reject({ receiptId: advance.id, reason: 'ZZ never arrived' });
  const left = await office.pending();
  ck('I8 approved or refused, a payment leaves the list', left.map((r) => r.id).join() === exact.id, `got ${left.map((r) => r.number).join(', ')}`);
  ck('I9 and the counts', (await badges()) === JSON.stringify({ myApprovals: 1, receipts: 1, depositReceipts: 0 }), await badges());
}

async function purge() {
  // A login has no organisation of its own; it goes by its address.
  await prisma.user.deleteMany({ where: { email: TENANT_LOGIN } });
  const org = await prisma.organization.findUnique({ where: { code: ORG_CODE }, select: { id: true } });
  if (!org) return;
  const where = { organizationId: org.id };
  const entries = (await prisma.journalEntry.findMany({ where, select: { id: true } })).map((e) => e.id);
  await prisma.journalLine.deleteMany({ where: { entryId: { in: entries } } });
  await prisma.journalEntry.updateMany({ where: { id: { in: entries } }, data: { reversesId: null } });
  await prisma.journalEntry.deleteMany({ where: { id: { in: entries } } });
  const rcpIds = (await prisma.receipt.findMany({ where, select: { id: true } })).map((r) => r.id);
  await prisma.receiptAllocationItem.deleteMany({ where: { allocation: { receiptId: { in: rcpIds } } } });
  await prisma.receiptAllocation.deleteMany({ where: { receiptId: { in: rcpIds } } });
  await prisma.receipt.updateMany({ where: { id: { in: rcpIds } }, data: { sourceReceiptId: null } });
  await prisma.receipt.deleteMany({ where: { id: { in: rcpIds } } });
  await prisma.deposit.deleteMany({ where });
  const invIds = (await prisma.invoice.findMany({ where, select: { id: true } })).map((i) => i.id);
  await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invIds } } });
  await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
  const leaseIds = (await prisma.lease.findMany({ where, select: { id: true } })).map((l) => l.id);
  await prisma.chargeRule.deleteMany({ where: { leaseId: { in: leaseIds } } });
  await prisma.leaseUnit.deleteMany({ where: { leaseId: { in: leaseIds } } });
  await prisma.lease.deleteMany({ where: { id: { in: leaseIds } } });
  const props = (await prisma.property.findMany({ where, select: { id: true } })).map((p) => p.id);
  await prisma.unit.deleteMany({ where: { propertyId: { in: props } } });
  await prisma.property.deleteMany({ where: { id: { in: props } } });
  await prisma.tenant.deleteMany({ where });
  await prisma.chargeType.deleteMany({ where });
  await prisma.glAccount.deleteMany({ where });
  await prisma.numberSequence.deleteMany({ where });
  await prisma.organization.delete({ where: { id: org.id } });
}

async function cleanup() {
  try { await purge(); 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); });
