/**
 * Functional smoke for what a bounced cheque does to an auto-created deposit.
 *
 * When a debit note carrying deposit charges is paid in full, approve() raises a
 * managed Deposit for it. That deposit posts nothing of its own — its held
 * balance is read from the INVOICE's credit to Deposits Held (2300), reached via
 * sourceInvoiceId. bounce() reverses the RECEIPT entry only, so before this fix
 * the invoice correctly re-opened while the deposit still read 100% held: money
 * that never cleared, sitting there ready to be applied to another note or
 * refunded out of the bank. The trial balance stayed balanced throughout, so
 * nothing would have flagged it.
 *
 * bounce() has never had any coverage at all; this is it.
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/bounce-deposit-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import type { Prisma } from '@prisma/client';
import { ApprovalService } from '../src/approvals/approval.service';
import { BillingService } from '../src/billing/billing.service';
import { invoiceArState } from '../src/billing/invoice-ar';
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 { issueInvoice, purgeSmokeApprover } from './_smoke-approval';
import { purgeSmokeLandlord, smokeLandlord } from './_smoke-company';

/** This smoke's own landlord company (see _smoke-company.ts). */
const LANDLORD = 'ZZBNC';

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 deps = { prisma, billing, approvals };

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-BNC';
const PROP = 'ZZ Bounce Property';
const TENANT = 'ZZ Bounce Tenant';
const DEP_CODE = 'ZZBDEP';

const owed = async (orgId: string, invoiceId: string) =>
  (await invoiceArState(prisma as unknown as Prisma.TransactionClient, orgId, invoiceId)).outstanding.toFixed(2);

/** The deposit's held balance, through the deposits module's own derivation
 *  (depositHeld) rather than a re-implementation of it here. */
async function heldOf(orgId: string, depositId: string): Promise<string> {
  const data = await deposits.settlementData(orgId, depositId);
  return data ? data.held : 'MISSING';
}

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');
  // A deposit-category charge type is what makes approve() raise a managed deposit.
  const depGl = await prisma.glAccount.findFirst({ where: { organizationId: orgId, role: 'DEPOSITS_HELD' }, select: { id: true } });
  if (!depGl) throw new Error('no 2300 deposits-held account');

  await purgeStale();

  const depCt = await prisma.chargeType.create({
    data: { organizationId: orgId, code: DEP_CODE, nameEn: 'ZZ Bounce Deposit', category: 'DEPOSIT', glAccountId: depGl.id, isActive: true, sortOrder: 996 },
  });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: TENANT } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: PROP, units: { create: [{ name: 'ZZ Bnc A' }] } },
    include: { units: true },
  });

  /** A lease whose first note carries rent plus a one-off deposit charge. */
  const mkLease = async (suffix: string) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `${REF}-${suffix}`, tenantId: tenant.id,
        status: 'ACTIVE', currency: 'HKD', startDate: new Date(`20${suffix}-01-01`), endDate: new Date('2100-01-01'), depositMonths: 0,
        units: { create: [{ unitId: property.units[0].id }] },
        chargeRules: { create: [
          { chargeTypeId: rentCt.id, amount: '5000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 },
          { chargeTypeId: depCt.id, amount: '2000', frequencyMonths: 0, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: true, sortOrder: 1 },
        ] },
      },
    });

  /** Issue the lease's first note and pay it in full, so a deposit is raised. */
  async function payInFull(leaseId: string, period: string) {
    const inv = await billing.generateDraft({ organizationId: orgId, leaseId, period });
    await issueInvoice(deps, orgId, inv.id);
    const total = await owed(orgId, inv.id);
    const r = await payments.recordBulkPayment({
      organizationId: orgId, tenantId: tenant.id, amount: total,
      allocations: [{ invoiceId: inv.id, amount: total }],
    });
    await payments.approve({ organizationId: orgId, receiptId: r.id });
    const dep = await prisma.deposit.findUnique({ where: { sourceInvoiceId: inv.id }, select: { id: true, status: true } });
    return { invoiceId: inv.id, receiptId: r.id, depositId: dep?.id ?? null, depositStatus: dep?.status ?? null };
  }

  console.log('A. Paying a note with deposit charges raises a managed deposit');
  const a = await payInFull((await mkLease('19')).id, '2019-01');
  ck('A1 a deposit was raised for the note', a.depositId !== null && a.depositStatus === 'HELD', `status ${a.depositStatus}`);
  ck('A2 and it reads the full amount held', (await heldOf(orgId, a.depositId!)) === '2000.00', `got ${await heldOf(orgId, a.depositId!)}`);
  ck('A3 the note is settled', (await owed(orgId, a.invoiceId)) === '0.00');

  console.log('');
  console.log('B. The cheque bounces — the deposit is money nobody handed over');
  await payments.bounce({ organizationId: orgId, receiptId: a.receiptId });
  ck('B1 the note is owed again in full', (await owed(orgId, a.invoiceId)) === '7000.00', `got ${await owed(orgId, a.invoiceId)}`);
  const voided = await prisma.deposit.findUniqueOrThrow({ where: { id: a.depositId! }, select: { status: true, sourceInvoiceId: true } });
  ck('B2 the deposit is voided', voided.status === 'VOID', `got ${voided.status}`);
  ck('B3 its held balance reads zero', (await heldOf(orgId, a.depositId!)) === '0.00', `got ${await heldOf(orgId, a.depositId!)} — it could be applied or refunded`);
  ck('B4 and it is unlinked, so re-paying the note can raise a fresh one', voided.sourceInvoiceId === null);

  let applied = false;
  try {
    await deposits.apply({ organizationId: orgId, depositId: a.depositId!, invoiceId: a.invoiceId, amount: '100' });
    applied = true;
  } catch { /* expected */ }
  ck('B5 a voided deposit cannot be applied to anything', !applied, 'money that never cleared was spendable');

  console.log('');
  console.log('C. Paying it again raises a real one');
  const total = await owed(orgId, a.invoiceId);
  const r2 = await payments.recordBulkPayment({
    organizationId: orgId, tenantId: tenant.id, amount: total,
    allocations: [{ invoiceId: a.invoiceId, amount: total }],
  });
  await payments.approve({ organizationId: orgId, receiptId: r2.id });
  const fresh = await prisma.deposit.findUnique({ where: { sourceInvoiceId: a.invoiceId }, select: { id: true, status: true } });
  ck('C1 a new deposit exists for the note', Boolean(fresh) && fresh!.id !== a.depositId, `got ${fresh?.id}`);
  ck('C2 and it holds the money', (await heldOf(orgId, fresh!.id)) === '2000.00', `got ${await heldOf(orgId, fresh!.id)}`);

  console.log('');
  console.log('D. A deposit that has already been used blocks the bounce instead');
  const leaseD = await mkLease('18');
  const d = await payInFull(leaseD.id, '2018-01');
  // Something to apply it against, then draw on the deposit.
  const target = await billing.generateDraft({ organizationId: orgId, leaseId: leaseD.id, period: '2018-02' });
  await issueInvoice(deps, orgId, target.id);
  await deposits.apply({ organizationId: orgId, depositId: d.depositId!, invoiceId: target.id, amount: '500' });

  let refused = '';
  try {
    await payments.bounce({ organizationId: orgId, receiptId: d.receiptId });
  } catch (e) {
    refused = e instanceof Error ? e.message : String(e);
  }
  ck('D1 the bounce is refused, naming the deposit', refused.includes('already been used'), `got "${refused}"`);
  const untouched = await prisma.receipt.findUniqueOrThrow({ where: { id: d.receiptId }, select: { status: true } });
  ck('D2 and nothing was half-done — the receipt is still approved', untouched.status === 'APPROVED', `got ${untouched.status}`);
  const depStill = await prisma.deposit.findUniqueOrThrow({ where: { id: d.depositId! }, select: { status: true } });
  ck('D3 the deposit is untouched too', depStill.status === 'PARTIALLY_APPLIED', `got ${depStill.status}`);
  ck('D4 and the applied amount still stands', (await owed(orgId, target.id)) === '4500.00', `got ${await owed(orgId, target.id)}`);
}

async function purgeStale() {
  const tenants = await prisma.tenant.findMany({ where: { name: TENANT }, select: { id: true } });
  const tenantIds = tenants.map((t) => t.id);
  if (tenantIds.length) {
    const deps2 = await prisma.deposit.findMany({ where: { tenantId: { in: tenantIds } }, select: { id: true } });
    const depIds = deps2.map((d) => d.id);
    if (depIds.length) {
      await prisma.depositAllocation.deleteMany({ where: { depositId: { in: depIds } } });
      await prisma.depositSettlementLine.deleteMany({ where: { settlement: { depositId: { in: depIds } } } }).catch(() => {});
      await prisma.depositSettlement.deleteMany({ where: { depositId: { in: depIds } } }).catch(() => {});
      await removeEntries(depIds);
    }
    const receipts = await prisma.receipt.findMany({ where: { tenantId: { in: tenantIds } }, select: { id: true } });
    const rIds = receipts.map((r) => r.id);
    if (rIds.length) {
      await prisma.receiptAllocationItem.deleteMany({ where: { allocation: { receiptId: { in: rIds } } } }).catch(() => {});
      await prisma.receiptAllocation.deleteMany({ where: { receiptId: { in: rIds } } });
      await removeEntries(rIds);
    }
  }
  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) {
      await prisma.deposit.updateMany({ where: { sourceInvoiceId: { in: invIds } }, data: { sourceInvoiceId: null } });
      await removeEntries(invIds);
      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(() => {});
  }
  if (tenantIds.length) {
    await prisma.deposit.deleteMany({ where: { tenantId: { in: tenantIds } } });
    await prisma.receipt.deleteMany({ where: { tenantId: { in: tenantIds } } });
  }
  const props = await prisma.property.findMany({ where: { name: 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: DEP_CODE } }).catch(() => {});
}

/** Journal entries for these sources, reversals first so the FK holds. */
async function removeEntries(sourceIds: string[]) {
  const entries = await prisma.journalEntry.findMany({
    where: { OR: [{ sourceId: { in: sourceIds } }, { lines: { some: { invoiceId: { in: sourceIds } } } }] },
    select: { id: true, reversesId: true },
  });
  const eids = entries.map((e) => e.id);
  if (!eids.length) return;
  await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } });
  const reversers = entries.filter((e) => e.reversesId).map((e) => e.id);
  if (reversers.length) await prisma.journalEntry.deleteMany({ where: { id: { in: reversers } } });
  await prisma.journalEntry.deleteMany({ where: { id: { in: eids } } });
}

async function cleanup() {
  try { await purgeSmokeApprover(prisma); await purgeSmokeLandlord(prisma, LANDLORD); 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); });
