/**
 * Functional smoke for the tenant's monthly statement.
 *
 * A statement is a lease's receivable over a period: the balance at the start,
 * every document that moved it — debit notes, payments, a deposit receipt's
 * credit, a security deposit used, a void, a bounce — with the balance running
 * down, then what is owed at the end by age and what the lease holds in
 * deposit and unused credit. This builds one lease's history day by day and
 * proves each of those reads back; that a carry-forward, which moves a balance
 * between the lease's own notes, prints nothing; that one period's closing is
 * the next one's opening; that the closings agree with AR Aging; and that the
 * shipped template renders it. Then sending: the PDF kept as it was sent, the
 * tenant notified and shown theirs alone, a second send replacing the first,
 * and a withdrawal taking it away.
 *
 * Its own organisation, so "every lease" means the fixture's. Standalone,
 * self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/statement-smoke.ts
 */
import 'reflect-metadata';
import { existsSync } from 'node:fs';
import { ConfigService } from '@nestjs/config';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Decimal } from '@rms/domain';
import { ApprovalService } from '../src/approvals/approval.service';
import { StorageService } from '../src/attachments/storage.service';
import { BillingService } from '../src/billing/billing.service';
import { NumberService } from '../src/common/number.service';
import { DepositsService } from '../src/deposits/deposits.service';
import { DocumentService } from '../src/documents/document.service';
import type { PdfService } from '../src/documents/pdf.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { ChannelDispatcher } from '../src/notifications/channel.dispatcher';
import { NotificationService } from '../src/notifications/notification.service';
import { PaymentsService } from '../src/payments/payments.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { ReportsService } from '../src/reports/reports.service';
import type { Statement, StatementQuery } from '../src/reports/reports.types';
import { StatementsService } from '../src/statements/statements.service';
import { portalRouter } from '../src/trpc/routers/portal.router';
import { reportsRouter } from '../src/trpc/routers/reports.router';
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 deposits = new DepositsService(prisma, ledger, numbers, approvals);
const reports = new ReportsService(prisma);
// The statement HTML reads neither storage nor the PDF renderer, and a sent
// statement only needs bytes: a stand-in renderer keeps Chromium out of the smoke.
const FAKE_PDF = '%PDF-1.4 zz statement';
const storage = new StorageService(new ConfigService());
const documents = new DocumentService(prisma, storage, { render: async () => Buffer.from(FAKE_PDF) } as unknown as PdfService);
const events = new EventEmitter2();
const notifications = new NotificationService(prisma, new ChannelDispatcher());
events.on('notify', (payload) => notifications.dispatch(payload));
const statementsSvc = new StatementsService(prisma, reports, documents, storage, events);

let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };

const ORG_CODE = 'ZZ-STM-ORG';

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'ZZ Statement Org', address: '6/F, ZZ Plaza', tel: '2866 0000' } })).id;
  for (const [docType, prefix] of [['INVOICE', 'ZSN-'], ['RECEIPT', 'ZSR-'], ['DEPOSIT_RECEIPT', 'ZSD-'], ['DEPOSIT', 'ZSP-'], ['LEASE', 'ZSL-']]) {
    await prisma.numberSequence.create({ data: { organizationId: orgId, docType, prefix, padding: 4 } });
  }
  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], ['4100', 'Management Fee Income', 'INCOME', null]] as const) {
    gl[code] = (await prisma.glAccount.create({ data: { organizationId: orgId, code, name, type, role } })).id;
  }
  const rent = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'RENT', nameEn: 'Rent', category: 'RECURRING', glAccountId: gl['4000'] } });
  const mgmt = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'MGMT', nameEn: 'Management Fee', category: 'RECURRING', glAccountId: gl['4100'] } });
  const landlord = await prisma.landlord.create({ data: { organizationId: orgId, code: 'ZZSTM', name: 'ZZ Statement Holdings Limited' } });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Statement Tenant', attention: 'Miss ZZ' } });
  await prisma.tenantCode.create({ data: { organizationId: orgId, tenantId: tenant.id, landlordId: landlord.id, code: 'ZZSTMT01' } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, landlordId: landlord.id, name: 'ZZ Statement Plaza', address: '9 ZZ Road, Kowloon Bay', units: { create: ['A', 'B', 'C', 'D', 'E'].map((name) => ({ name })) } },
    include: { units: true },
  });
  const mkLease = (ref: string, units: number[], status: 'ACTIVE' | 'ENDED' = 'ACTIVE') =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `ZZ-STM-${ref}`, tenantId: tenant.id, status, currency: 'HKD',
        startDate: new Date('2025-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
        units: { create: units.map((i) => ({ unitId: property.units[i].id })) },
        chargeRules: { create: [
          { chargeTypeId: rent.id, amount: '6000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 },
          { chargeTypeId: mgmt.id, amount: '112', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 1 },
        ] },
      },
    });
  const L1 = await mkLease('L1', [0, 1]);
  const L2 = await mkLease('L2', [2]);
  const quiet = await mkLease('QUIET', [3]);
  const old = await mkLease('OLD', [4], 'ENDED');

  /** Does `step` as if on `day`: whatever it posts is dated that day, and a
   *  note it issues was issued that day. */
  const at = async <T>(day: string, step: () => Promise<T>): Promise<T> => {
    const t0 = new Date(Date.now() - 1);
    const out = await step();
    const when = new Date(`${day}T12:00:00+08:00`);
    await prisma.journalEntry.updateMany({ where: { organizationId: orgId, createdAt: { gte: t0 } }, data: { entryDate: when } });
    await prisma.invoice.updateMany({ where: { organizationId: orgId, issueDate: { gte: t0 } }, data: { issueDate: when } });
    return out;
  };
  const issue = (period: string) => async () => {
    const draft = await billing.generateDraft({ organizationId: orgId, leaseId: L1.id, period });
    return billing.issue({ organizationId: orgId, invoiceId: draft.id });
  };
  const pay = (allocations: { invoiceId: string; amount: string }[], day: string) => async () => {
    const amount = allocations.reduce((t, a) => t.plus(a.amount), new Decimal(0)).toFixed(2);
    const r = await payments.recordBulkPayment({ organizationId: orgId, tenantId: tenant.id, amount, allocations, receivedDate: new Date(day), reference: 'CHQ 123456' });
    await payments.approve({ organizationId: orgId, receiptId: r.id });
    return r;
  };
  const advance = (leaseId: string, amount: string, day: string) => async () => {
    const r = await payments.recordDepositReceipt({ organizationId: orgId, tenantId: tenant.id, leaseId, amount, receivedDate: new Date(day) });
    await payments.approve({ organizationId: orgId, receiptId: r.id });
    return r;
  };

  const dep = await at('2025-08-01', () => deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: L1.id, amount: '12000', receivedDate: '2025-08-01' }));
  const n1 = await at('2025-08-01', issue('2025-08'));
  await at('2025-08-20', pay([{ invoiceId: n1.id, amount: '6112' }], '2025-08-20'));
  const n2 = await at('2025-09-01', issue('2025-09'));
  const r2 = await at('2025-09-30', pay([{ invoiceId: n2.id, amount: '3000' }], '2025-09-30'));
  const n3 = await at('2025-10-01', issue('2025-10'));
  const r3 = await at('2025-10-15', pay([{ invoiceId: n2.id, amount: '1000' }, { invoiceId: n3.id, amount: '1000' }], '2025-10-15'));
  await at('2025-10-10', advance(L2.id, '800', '2025-10-10'));
  const dr = await at('2025-10-20', advance(L1.id, '500', '2025-10-20'));
  await at('2025-10-22', () => deposits.apply({ organizationId: orgId, depositId: dep.id, invoiceId: n3.id, amount: '1000' }));
  const n4 = await at('2025-10-24', issue('2025-11'));
  await at('2025-10-25', () => billing.voidInvoice({ organizationId: orgId, invoiceId: n4.id }));
  await at('2025-10-26', () => payments.bounce({ organizationId: orgId, receiptId: r2.id }));
  const dec = await billing.generateDraft({ organizationId: orgId, leaseId: L1.id, period: '2025-12' });
  await at('2025-10-27', () => billing.carryForward({ organizationId: orgId, invoiceId: n3.id, targetPeriod: '2025-12' }));
  await at('2025-11-05', pay([{ invoiceId: n2.id, amount: '100' }], '2025-11-05'));
  console.log('Fixture: one lease from August to November 2025 — notes, payments, credit, a deposit used, a void, a bounce, a carry-forward\n');

  const base: StatementQuery = { from: '2025-09-01', to: '2025-10-28', agingBasis: 'due', openingItems: false, groupEntries: true };
  const of = async (q: Partial<StatementQuery>, leaseId = L1.id): Promise<Statement | undefined> =>
    (await reports.statements(orgId, { ...base, ...q })).statements.find((s) => s.leaseId === leaseId);
  const s = (await of({}))!;
  const n = (inv: { number: string | null }) => inv.number ?? '';

  console.log('R. Every document of the period, the balance running down');
  const shape = s.rows.map((r) => [r.kind, r.number, r.debit ?? '', r.credit ?? '', r.balance].join(' '));
  const want = [
    ['BALANCE_BF', '', '', '', '0.00'],
    ['INVOICE', n(n2), '6112.00', '', '6112.00'],
    ['PAYMENT', r2.number, '', '3000.00', '3112.00'],
    ['INVOICE', n(n3), '6112.00', '', '9224.00'],
    ['PAYMENT', r3.number, '', '2000.00', '7224.00'],
    ['CREDIT_APPLIED', dr.number, '', '500.00', '6724.00'],
    ['DEPOSIT_APPLIED', dep.number, '', '1000.00', '5724.00'],
    ['INVOICE', n(n4), '6112.00', '', '11836.00'],
    ['VOID', n(n4), '', '6112.00', '5724.00'],
    ['REVERSAL', r2.number, '3000.00', '', '8724.00'],
  ].map((r) => r.join(' '));
  ck('R1 the rows, in order, with the balance after each', JSON.stringify(shape) === JSON.stringify(want), `\n      got  ${shape.join('\n           ')}\n      want ${want.join('\n           ')}`);
  ck('R2 the carry-forward printed nothing', !s.rows.some((r) => r.description.toLowerCase().includes('carr')));
  ck('R3 opening 0, closing 8,724; debits 21,336 and credits 12,612 between', s.opening === '0.00' && s.closing === '8724.00' && s.debit === '21336.00' && s.credit === '12612.00',
    JSON.stringify([s.opening, s.closing, s.debit, s.credit]));
  ck('R4 rows are dated the day they posted', s.rows[1].date === '2025-09-01' && s.rows[2].date === '2025-09-30' && s.rows[9].date === '2025-10-26', JSON.stringify(s.rows.map((r) => r.date)));
  ck('R5 a note reads its period and charges', s.rows[1].description === 'Sep 2025 — Rent, Management Fee', s.rows[1].description);
  ck('R6 a payment reads how it was paid, and its own amount', s.rows[4].description === 'Payment — CHQ 123456' && s.rows[4].amount === '2000.00', JSON.stringify(s.rows[4]));
  ck('R7 the payment received after the period is not on it', !s.rows.some((r) => r.date === '2025-11-05'));

  console.log('\nA. What is owed at the end, and what is held');
  const dueN2 = (await prisma.invoice.findUniqueOrThrow({ where: { id: n2.id } })).dueDate.toISOString().slice(0, 10);
  const age = Math.round((Date.parse('2025-10-28') - Date.parse(dueN2)) / 86_400_000);
  const n2Bucket = age <= 0 ? 'notYetDue' : age <= 30 ? 'd0_30' : age <= 60 ? 'd31_60' : age <= 90 ? 'd61_90' : 'over90';
  ck(`A1 Sep's 4,612 is aged from its due date (${dueN2}, ${age} days)`, s.aging[n2Bucket] === '4612.00', JSON.stringify(s.aging));
  ck('A2 the 4,112 carried onto December\'s draft is not yet due', s.aging.notYetDue === (n2Bucket === 'notYetDue' ? '8724.00' : '4112.00'), JSON.stringify(s.aging));
  const agingSum = Object.values(s.aging).reduce((t, v) => t.plus(v), new Decimal(0));
  ck('A3 the buckets add up to the closing balance', agingSum.toFixed(2) === s.closing, agingSum.toFixed(2));
  ck('A4 deposit remained: 12,000 less the 1,000 used', s.deposit === '11000.00', s.deposit);
  ck('A5 the deposit receipt was drawn in full, so nothing unallocated', s.unallocated === '0.00', s.unallocated);
  const s2 = await of({}, L2.id);
  ck('A6 the other lease holds its 800 unused, with nothing else to show', s2?.unallocated === '800.00' && s2.closing === '0.00' && s2.rows.length === 1 && s2.active, JSON.stringify(s2 && [s2.unallocated, s2.rows.length]));
  const byIssue = (await of({ agingBasis: 'issue' }))!;
  ck('A7 by issue date the buckets still add up', Object.values(byIssue.aging).reduce((t, v) => t.plus(v), new Decimal(0)).toFixed(2) === byIssue.closing);

  console.log('\nO. The opening balance, two ways');
  const sep = (await of({ to: '2025-09-30' }))!;
  const oct = (await of({ from: '2025-10-01' }))!;
  ck('O1 one period\'s closing is the next one\'s opening', sep.closing === '3112.00' && oct.opening === '3112.00', JSON.stringify([sep.closing, oct.opening]));
  ck('O2 by default it is one balance b/f line', oct.rows[0].kind === 'BALANCE_BF' && oct.rows[0].balance === '3112.00' && oct.rows[0].date === '2025-09-30', JSON.stringify(oct.rows[0]));
  const items = (await of({ from: '2025-10-01', openingItems: true }))!;
  ck('O3 asked for, each note still owing is listed instead', items.rows[0].kind === 'OPENING_ITEM' && items.rows[0].number === n(n2) && items.rows[0].debit === '3112.00' && items.rows[0].balance === '3112.00',
    JSON.stringify(items.rows[0]));
  ck('O4 and the balance runs on from there to the same close', items.rows.at(-1)!.balance === oct.closing && oct.closing === s.closing);

  console.log('\nG. One line per document, or per note it paid');
  const split = (await of({ groupEntries: false }))!;
  const r3rows = split.rows.filter((r) => r.number === r3.number);
  ck('G1 split, the payment of two notes is two lines naming each', r3rows.length === 2 && r3rows.every((r) => r.credit === '1000.00') &&
    r3rows.some((r) => r.description.includes(n(n2))) && r3rows.some((r) => r.description.includes(n(n3))), JSON.stringify(r3rows.map((r) => r.description)));
  ck('G2 and closes on the same balance', split.closing === s.closing && split.rows.at(-1)!.balance === s.closing);

  console.log('\nW. Which leases, and what agrees with them');
  const all = (await reports.statements(orgId, base)).statements;
  ck('W1 an active lease with nothing to show is there, marked so', all.some((x) => x.leaseId === quiet.id && !x.active));
  ck('W2 an ended lease with nothing to show is not', !all.some((x) => x.leaseId === old.id));
  ck('W3 asked for one lease, that one only', (await reports.statements(orgId, { ...base, leaseIds: [L2.id] })).statements.map((x) => x.leaseId).join() === L2.id);
  const aging = await reports.arAging(orgId, base.to);
  const total = all.reduce((t, x) => t.plus(x.closing), new Decimal(0)).toFixed(2);
  ck('W4 the closings total AR Aging\'s', aging.groups.find((g) => g.currency === 'HKD')?.totals.total === total, `${total} vs ${aging.groups[0]?.totals.total}`);
  ck('W5 the tenant\'s code under the company, and the premises', s.tenantCode === 'ZZSTMT01' && s.landlordCode === 'ZZSTM' && s.building === 'ZZ Statement Plaza' && s.units.join() === 'A,B',
    JSON.stringify([s.tenantCode, s.landlordCode, s.building, s.units]));
  const nov = (await of({ to: '2025-11-30' }))!;
  ck('W6 November\'s payment is on a statement that runs to it', nov.rows.some((r) => r.date === '2025-11-05' && r.credit === '100.00') && nov.closing === '8624.00', nov.closing);

  console.log('\nT. The list endpoint, and the shipped template');
  const caller = reportsRouter.createCaller({
    prisma, organizationId: orgId, reports, statements: statementsSvc,
    user: { id: 'zz', email: 'zz@rms.local', name: 'ZZ', tenantId: null, mustChangePassword: false, permissions: ['finance.report'], roles: [] },
  } as unknown as Context);
  const listed = await caller.statements({ from: base.from, to: base.to });
  const mine = listed.statements.find((x) => x.leaseId === L1.id);
  ck('T1 the list carries the totals and leaves the lines out', mine?.closing === '8724.00' && !('rows' in (mine ?? {})));
  const { html } = await documents.statementsHtml(orgId, [s, s2!], base);
  ck('T2 a page per statement', (html.match(/<section class="page">/g) ?? []).length === 2);
  ck('T3 it prints the title, the tenant and code, and the period', html.includes('Monthly Statement') && html.includes('ZZ Statement Tenant (ZZSTMT01)') && html.includes('01/09/2025 To 28/10/2025'));
  ck('T4 each line\'s date, number and running balance', html.includes('30/09/2025') && html.includes(r2.number) && html.includes('8,724.00') && html.includes('11,836.00'));
  ck('T5 the aging, the deposit and the credit held', html.includes('Not Yet Due') && html.includes('11,000.00') && html.includes('800.00'));
  ck('T6 under the organisation\'s letterhead', html.includes('ZZ Statement Org') && html.includes('6/F, ZZ Plaza'));
  ck('T7 the units and building head the address', html.includes('A, B, ZZ Statement Plaza') && html.includes('9 ZZ Road'));
  const tpl = await prisma.documentTemplate.findFirst({ where: { organizationId: orgId, docType: 'STATEMENT' } });
  ck('T8 the statement template was seeded as its own', tpl?.name === 'Monthly Statement');
  void dec;

  console.log('\nS. Sending to the tenant');
  await prisma.tenant.update({ where: { id: tenant.id }, data: { email: 'zz-stm@rms.local' } });
  await prisma.notificationTemplate.create({
    data: { organizationId: orgId, event: 'STATEMENT_SENT', channel: 'EMAIL', locale: 'zh', recipient: 'TENANT', subject: 'S {{period}}', body: '{{leaseReference}} {{period}} {{balance}}' },
  });
  ck('S0 before sending, the list marks nothing sent, and the tenant cannot sign in', (await caller.statements({ from: base.from, to: base.to })).statements.every((x) => x.sent === null && !x.portalLogin));
  const first = await caller.sendStatements({ ...base, leaseIds: [L1.id, L2.id] });
  const rows = await prisma.sentStatement.findMany({ where: { organizationId: orgId }, orderBy: { sentAt: 'asc' } });
  const r1 = rows.find((r) => r.leaseId === L1.id);
  ck('S1 both leases sent, each kept with the balance it closed on', first.sent === 2 && rows.length === 2 && r1?.closing.toFixed(2) === '8724.00', JSON.stringify([first, rows.length, r1?.closing]));
  ck('S2 the PDF is kept as it was sent', !!r1 && (await storage.read(r1.storageKey)).toString() === FAKE_PDF);
  const outbox = await prisma.notificationOutbox.findMany({ where: { organizationId: orgId, event: 'STATEMENT_SENT' } });
  ck('S3 the tenant is notified of each, with the lease, period and balance', outbox.length === 2 &&
    outbox.some((o) => o.body.includes('ZZ-STM-L1') && o.body.includes('2025-09-01 – 2025-10-28') && o.body.includes('8,724.00') && o.recipient === 'zz-stm@rms.local'),
    JSON.stringify(outbox.map((o) => [o.recipient, o.body, o.status])));
  const marked = (await caller.statements({ from: base.from, to: base.to })).statements;
  ck('S4 the list marks them sent for this period', marked.find((x) => x.leaseId === L1.id)?.sent?.id === r1?.id && marked.find((x) => x.leaseId === quiet.id)?.sent === null);
  ck('S5 and not for another period', (await caller.statements({ from: '2025-10-01', to: base.to })).statements.every((x) => x.sent === null));

  const login = await prisma.user.create({ data: { email: 'zz-stm-tenant@rms.local', name: 'ZZ STM', passwordHash: 'x', tenantId: tenant.id } });
  const stranger = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Statement Stranger' } });
  const asTenant = (tenantId: string) => portalRouter.createCaller({
    prisma, organizationId: orgId, statements: statementsSvc,
    user: { id: login.id, email: 'zz', name: 'ZZ', tenantId, mustChangePassword: false, permissions: [], roles: [] },
  } as unknown as Context);
  ck('S6 now the tenant has a login, the list says so', (await caller.statements({ from: base.from, to: base.to })).statements.every((x) => x.portalLogin));
  const mineInPortal = await asTenant(tenant.id).statements();
  ck('S7 the tenant sees both in the portal, with period and balance', mineInPortal.length === 2 &&
    mineInPortal.some((x) => x.leaseReference === 'ZZ-STM-L1' && x.from === '2025-09-01' && x.to === '2025-10-28' && x.closing === '8724.00'), JSON.stringify(mineInPortal));
  ck('S8 another tenant sees none of them', (await asTenant(stranger.id).statements()).length === 0);
  const file = await statementsSvc.file(orgId, r1!.id);
  ck('S9 the file says whose it is', file.tenantId === tenant.id && file.filename === 'statement-ZZ-STM-L1-2025-10-28.pdf', JSON.stringify([file.tenantId, file.filename]));

  await caller.sendStatements({ ...base, leaseIds: [L1.id] });
  const again = await prisma.sentStatement.findMany({ where: { leaseId: L1.id } });
  ck('S10 sending the same period again replaces it — one row, a new file', again.length === 1 && again[0].id === r1!.id && again[0].storageKey !== r1!.storageKey);
  ck('S11 and the old file is gone', !existsSync(storage.absolute(r1!.storageKey)) && existsSync(storage.absolute(again[0].storageKey)));
  await caller.sendStatements({ ...base, from: '2025-10-01', leaseIds: [L1.id] });
  ck('S12 another period is a statement of its own', (await asTenant(tenant.id).statements()).length === 3);

  await caller.withdrawStatement({ id: again[0].id });
  ck('S13 withdrawn, it leaves the portal and its file goes', !(await asTenant(tenant.id).statements()).some((x) => x.id === again[0].id) && !existsSync(storage.absolute(again[0].storageKey)));
  ck('S14 withdrawing it twice is refused', (await caller.withdrawStatement({ id: again[0].id }).then(() => '', (e: Error) => e.message)) === 'Statement not found');
}

async function purge() {
  await prisma.user.deleteMany({ where: { email: 'zz-stm-tenant@rms.local' } });
  const org = await prisma.organization.findUnique({ where: { code: ORG_CODE }, select: { id: true } });
  if (!org) return;
  const where = { organizationId: org.id };
  for (const s of await prisma.sentStatement.findMany({ where, select: { storageKey: true } })) await storage.remove(s.storageKey);
  await prisma.sentStatement.deleteMany({ where });
  await prisma.notificationOutbox.deleteMany({ where });
  await prisma.notificationTemplate.deleteMany({ where });
  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 } } });
  const depIds = (await prisma.deposit.findMany({ where, select: { id: true } })).map((d) => d.id);
  await prisma.depositAllocation.deleteMany({ where: { depositId: { in: depIds } } });
  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 }); // its code goes with it
  await prisma.landlord.deleteMany({ where });
  await prisma.chargeType.deleteMany({ where });
  await prisma.glAccount.deleteMany({ where });
  await prisma.numberSequence.deleteMany({ where });
  await prisma.documentTemplate.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); });
