/**
 * Functional smoke: each of the office's bank accounts has its own account in
 * the chart of accounts.
 *
 * Every bank account number has its own code in the office's ERP, but the
 * ledger had one Bank account: whichever account the money went into, it posted
 * there. Now the chart marks its bank accounts, each collection account names
 * the one it posts to, and money posts to the bank it actually went through —
 * the owner's choice: a payment of a debit note to the account printed on the
 * note, a lease's prepayments and security deposits to the lease's collection
 * account, and its refunds out of it. A collection account naming none posts
 * to the chart's Bank, as every one did before.
 *
 * What has to hold, and is asserted: the chart's rules for a bank account (an
 * asset; no system account but the Bank; no charge's account, and never
 * picked as one); a collection account takes only a bank account; one payment
 * over notes of two accounts debits both; a bounce takes it back out of the
 * same two; a note keeps the account it went out with when its lease changes
 * account; the collections report counts every bank; and the ledger balances.
 *
 * Runs in its own organisation. Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/bank-ledger-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Decimal, sum } from '@rms/domain';
import { ApprovalService } from '../src/approvals/approval.service';
import { BillingService } from '../src/billing/billing.service';
import { NumberService } from '../src/common/number.service';
import { DepositsService } from '../src/deposits/deposits.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { PaymentsService } from '../src/payments/payments.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { ReportsService } from '../src/reports/reports.service';
import { bankAccountsRouter } from '../src/trpc/routers/bank-accounts.router';
import { chargeTypesRouter } from '../src/trpc/routers/charge-types.router';
import { chartOfAccountsRouter } from '../src/trpc/routers/chart-of-accounts.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 deposits = new DepositsService(prisma, ledger, numbers, approvals);
const reports = new ReportsService(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 ORG_CODE = 'ZZ-BGL-ORG';

function staffCtx(orgId: string): Context {
  const user: AuthUser = {
    id: 'zz-bgl-staff', email: 'zz-bgl@rms.local', name: 'ZZ BGL', tenantId: null, mustChangePassword: false, roles: ['ADMIN'],
    permissions: ['gl-account.read', 'gl-account.create', 'gl-account.update', 'bank-account.read', 'bank-account.create', 'bank-account.update', 'charge-type.create'],
  };
  return { prisma, user, organizationId: orgId } as unknown as Context;
}

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'ZZ Bank ledger smoke org' } })).id;
  for (const [docType, prefix] of [['INVOICE', 'ZBN-'], ['RECEIPT', 'ZBR-'], ['DEPOSIT_RECEIPT', 'ZBD-'], ['DEPOSIT', 'ZBP-'], ['LEASE', 'ZBL-']]) {
    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'],
    ['2310', 'Refunds Payable', 'LIABILITY', 'REFUNDS_PAYABLE'], ['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, isBank: role === 'BANK' } })).id;
  }
  /** Debits less credits: what an asset account holds. */
  const held = async (accountId: string) => {
    const lines = await prisma.journalLine.findMany({ where: { accountId }, select: { direction: true, amount: true } });
    return lines.reduce((a, l) => a.plus(new Decimal(l.amount.toString()).times(l.direction === 'DEBIT' ? 1 : -1)), new Decimal(0)).toFixed(2);
  };
  const chart = chartOfAccountsRouter.createCaller(staffCtx(orgId));
  const banks = bankAccountsRouter.createCaller(staffCtx(orgId));
  const charges = chargeTypesRouter.createCaller(staffCtx(orgId));

  console.log('A. The chart marks its bank accounts');
  const hsbc = await chart.create({ code: '1110-01-0001', name: 'ZZ HSBC rent account', isBank: true });
  const hangSeng = await chart.create({ code: '1110-02-0001', name: 'ZZ Hang Seng rent account', isBank: true });
  const listed = (await chart.list()).find((a) => a.id === hsbc.id);
  ck('A1 an account is made a bank account, an asset by its code', listed?.isBank === true && listed.type === 'ASSET', JSON.stringify(listed));
  ck('A2 a bank account must be an asset', (await refused(() => chart.create({ code: '4110-01-0001', name: 'ZZ not an asset', isBank: true }))).includes('must be an asset account'));
  ck('A3 the system Bank stays a bank account', (await refused(() => chart.update({ id: gl['1000'], isBank: false }))).includes('always a bank account'));
  ck('A4 no other system account can be one', (await refused(() => chart.update({ id: gl['1100'], isBank: true }))).includes('cannot be a bank account'));
  const otherAsset = await chart.create({ code: '1500-01-0001', name: 'ZZ other asset' });
  await prisma.chargeType.create({ data: { organizationId: orgId, code: 'ZZ_ASSET', nameEn: 'Asset charge', category: 'ONE_OFF', glAccountId: otherAsset.id } });
  ck("A5 nor can a charge's account", (await refused(() => chart.update({ id: otherAsset.id, isBank: true }))).includes("charge's account"));
  ck("A6 and a bank account is never picked as a charge's", (await refused(() => charges.create({ code: 'ZZ_INTO_BANK', nameEn: 'Into the bank', category: 'ONE_OFF', glAccountId: hsbc.id }))).includes("bank account cannot be a charge's account"));

  console.log('\nB. A collection account names the bank account it posts to');
  const base = { bankName: 'ZZ Bank', accountName: 'ZZ Holdings Ltd', isActive: true };
  ck('B1 only a bank account will do', (await refused(() => banks.create({ ...base, name: 'ZZ wrong', accountNumber: '000-0', isCollectionAgent: false, glAccountId: gl['1100'] }))).includes("chart's bank accounts"));
  const ba1 = await banks.create({ ...base, name: 'ZZ HSBC', accountNumber: '111-111', isCollectionAgent: false, glAccountId: hsbc.id });
  const ba2 = await banks.create({ ...base, name: 'ZZ Hang Seng', accountNumber: '222-222', isCollectionAgent: false, glAccountId: hangSeng.id });
  const ba3 = await banks.create({ ...base, name: 'ZZ Default', accountNumber: '333-333', isCollectionAgent: true });
  const bankList = await banks.list();
  ck('B2 the list gives each its account, and the one naming none none', bankList.find((b) => b.id === ba1.id)?.account?.code === '1110-01-0001' && bankList.find((b) => b.id === ba3.id)?.account === null);
  ck('B3 a bank account a collection account posts to stays one', (await refused(() => chart.update({ id: hsbc.id, isBank: false }))).includes('give it another account first'));
  await banks.update({ id: ba1.id, ...base, name: 'ZZ HSBC', accountNumber: '111-111', isCollectionAgent: false });
  ck('B4 an update that leaves the account out keeps it', (await prisma.bankAccount.findUniqueOrThrow({ where: { id: ba1.id } })).glAccountId === hsbc.id);

  console.log('\nC. A payment posts to the bank of the account its note printed');
  const rent = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'RENT', nameEn: 'Rent', category: 'RECURRING', glAccountId: gl['4000'] } });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Bank Tenant' } });
  const property = await prisma.property.create({ data: { organizationId: orgId, name: 'ZZ Bank Property', units: { create: [{ name: 'A' }, { name: 'B' }, { name: 'C' }] } }, include: { units: true } });
  const mkLease = (ref: string, unit: number, monthly: string, bankAccountId: string | null) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `ZZ-BGL-${ref}`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD', bankAccountId,
        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 }] },
      },
    });
  const L1 = await mkLease('L1', 0, '1000', ba1.id);
  const L2 = await mkLease('L2', 1, '500', ba2.id);
  const L3 = await mkLease('L3', 2, '300', null);
  const issue = async (leaseId: string, period: string) => {
    const draft = await billing.generateDraft({ organizationId: orgId, leaseId, period });
    return billing.issue({ organizationId: orgId, invoiceId: draft.id });
  };
  const pay = async (notes: { id: string; amount: string }[]) => {
    const receipt = await payments.recordBulkPayment({
      organizationId: orgId, tenantId: tenant.id, amount: sum(notes.map((n) => n.amount)).toFixed(2),
      allocations: notes.map((n) => ({ invoiceId: n.id, amount: n.amount })),
    });
    return payments.approve({ organizationId: orgId, receiptId: receipt.id });
  };
  const l1Jan = await issue(L1.id, '2020-01');
  await pay([{ id: l1Jan.id, amount: '1000' }]);
  ck('C1 L1’s note, printed with the HSBC account, is paid into HSBC', (await held(hsbc.id)) === '1000.00' && (await held(hangSeng.id)) === '0.00' && (await held(gl['1000'])) === '0.00',
    `${await held(hsbc.id)} / ${await held(hangSeng.id)} / ${await held(gl['1000'])}`);
  const l1Feb = await issue(L1.id, '2020-02');
  const l2Feb = await issue(L2.id, '2020-02');
  const both = await pay([{ id: l1Feb.id, amount: '1000' }, { id: l2Feb.id, amount: '500' }]);
  const bothEntry = await prisma.journalEntry.findFirstOrThrow({ where: { sourceType: 'RECEIPT', sourceId: both.id, reversesId: null }, include: { lines: true } });
  const debits = bothEntry.lines.filter((l) => l.direction === 'DEBIT').map((l) => `${l.accountId === hsbc.id ? 'HSBC' : l.accountId === hangSeng.id ? 'HS' : '?'}=${l.amount.toFixed(2)}`).sort().join(' ');
  ck('C2 one payment over two accounts’ notes debits both, each its note’s part', debits === 'HS=500.00 HSBC=1000.00', debits);
  const l3Jan = await issue(L3.id, '2020-01');
  await pay([{ id: l3Jan.id, amount: '300' }]);
  ck('C3 a note whose account names no bank account is paid into the chart’s Bank', (await held(gl['1000'])) === '300.00', await held(gl['1000']));
  const cash = await reports.collections(orgId, '2019-01-01', '2100-01-01');
  ck('C4 the collections report counts every bank', cash.groups[0]?.total === '2800.00', JSON.stringify(cash.groups.map((g) => g.total)));
  await payments.bounce({ organizationId: orgId, receiptId: both.id, reason: 'ZZ bounced' });
  ck('C5 a bounce takes it back out of the same two', (await held(hsbc.id)) === '1000.00' && (await held(hangSeng.id)) === '0.00', `${await held(hsbc.id)} / ${await held(hangSeng.id)}`);
  const l1Mar = await issue(L1.id, '2020-03');
  await prisma.lease.update({ where: { id: L1.id }, data: { bankAccountId: ba2.id } });
  await pay([{ id: l1Mar.id, amount: '1000' }]);
  ck('C6 a note keeps the account it went out with when its lease changes account', (await held(hsbc.id)) === '2000.00' && (await held(hangSeng.id)) === '0.00', `${await held(hsbc.id)} / ${await held(hangSeng.id)}`);

  console.log('\nD. A lease’s prepayments, deposits and refunds use the lease’s account');
  const prepaid = await payments.recordDepositReceipt({ organizationId: orgId, tenantId: tenant.id, leaseId: L2.id, amount: '200' });
  await payments.approve({ organizationId: orgId, receiptId: prepaid.id });
  ck('D1 a deposit receipt for L2 is banked in Hang Seng', (await held(hangSeng.id)) === '200.00', await held(hangSeng.id));
  const deposit = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: L2.id, amount: '2000' });
  ck('D2 so is the security deposit received for it', (await held(hangSeng.id)) === '2200.00', await held(hangSeng.id));
  await deposits.settle({ organizationId: orgId, depositId: deposit.id, settledByUserId: null });
  await deposits.disburseRefund({ organizationId: orgId, depositId: deposit.id });
  ck('D3 and its refund is paid out of Hang Seng', (await held(hangSeng.id)) === '200.00', await held(hangSeng.id));
  await deposits.create({ organizationId: orgId, tenantId: tenant.id, amount: '700' });
  ck('D4 a deposit for no lease goes to the default collection account — here naming none, so the chart’s Bank', (await held(gl['1000'])) === '1000.00', await held(gl['1000']));

  console.log('\nE. The ledger');
  const lines = await prisma.journalLine.findMany({ where: { account: { organizationId: orgId } }, select: { direction: true, amount: true } });
  const dr = sum(lines.filter((l) => l.direction === 'DEBIT').map((l) => l.amount.toString()));
  const cr = sum(lines.filter((l) => l.direction === 'CREDIT').map((l) => l.amount.toString()));
  ck('E1 debits equal credits', dr.equals(cr), `${dr.toFixed(2)} vs ${cr.toFixed(2)}`);
}

async function purge() {
  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 } } });
  const depIds = (await prisma.deposit.findMany({ where, select: { id: true } })).map((d) => d.id);
  const setIds = (await prisma.depositSettlement.findMany({ where: { depositId: { in: depIds } }, select: { id: true } })).map((s) => s.id);
  await prisma.depositSettlementLine.deleteMany({ where: { settlementId: { in: setIds } } });
  await prisma.depositSettlement.deleteMany({ where: { id: { in: setIds } } });
  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 });
  await prisma.chargeType.deleteMany({ where });
  await prisma.bankAccount.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); });
