/**
 * Functional smoke for the two money movements that could not be undone.
 *
 * Carry-forward posts an AR→AR transfer, so its line cannot be deleted
 * (removeLine refuses it) and neither note can be voided (both branches refuse
 * a note carrying one). Booked into the wrong period it was permanent — and the
 * source silently left interest accrual on the way, because it reads PAID.
 *
 * A deposit application posts DR Deposits Held / CR AR with nothing to reverse
 * it: reverseSettlement only knows about allocations a settlement created, and
 * voidInvoice refuses an invoice with AR movement from a non-INVOICE source,
 * which is exactly what apply() posted. A wrong amount or the wrong invoice,
 * both easy from the ordinary dialog, needed DBA surgery.
 *
 * The assertions that matter are the ledger ones: after an undo the AR position
 * and the deposit's held balance must be exactly what they were before, since
 * both are derived and everything else follows from them.
 *
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/undo-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import type { JournalSourceType, 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 { 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 = 'ZZUND';

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 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-UND';
const PROP = 'ZZ Undo Property';
const TENANT = 'ZZ Undo Tenant';

const owed = async (orgId: string, invoiceId: string) =>
  (await invoiceArState(prisma as unknown as Prisma.TransactionClient, orgId, invoiceId)).outstanding.toFixed(2);
const held = async (orgId: string, depositId: string) => (await deposits.settlementData(orgId, depositId))!.held;
const statusOf = async (id: string) => (await prisma.invoice.findUniqueOrThrow({ where: { id }, select: { status: true } })).status;

/** Every journal line ever written for this org's AR + deposits, summed. The
 *  books must balance before and after an undo — a compensating entry that only
 *  half-lands would show up here and nowhere else. */
async function trialBalanced(orgId: string): Promise<boolean> {
  const lines = await prisma.journalLine.findMany({
    where: { entry: { organizationId: orgId } },
    select: { direction: true, amount: true },
  });
  let dr = 0, cr = 0;
  for (const l of lines) (l.direction === 'DEBIT' ? (dr += Number(l.amount)) : (cr += Number(l.amount)));
  return Math.abs(dr - cr) < 0.005;
}

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 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 Und A' }] } },
    include: { units: true },
  });
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `${REF}-1`, tenantId: tenant.id,
      status: 'ACTIVE', currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
      units: { create: [{ unitId: property.units[0].id }] },
      chargeRules: { create: [{ chargeTypeId: rentCt.id, amount: '8000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 }] },
    },
  });

  console.log('A. A carry-forward booked into the wrong month can be taken back');
  const src = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2019-01' });
  await issueInvoice(deps, orgId, src.id);
  const before = await owed(orgId, src.id);
  ck('A1 the source owes its full amount', before === '8000.00', `got ${before}`);

  const target = await billing.carryForward({ organizationId: orgId, invoiceId: src.id, targetPeriod: '2019-05' });
  ck('A2 the balance moved off the source', (await owed(orgId, src.id)) === '0.00');
  ck('A3 which now reads PAID without anybody paying', (await statusOf(src.id)) === 'PAID');
  const bf = (await prisma.invoiceLine.findMany({ where: { invoiceId: target.id, kind: 'OVERDUE_CARRYFORWARD' } }))[0];
  ck('A4 and onto the target as a b/f line', Number(bf?.amount) === 8000, `got ${bf?.amount}`);

  await billing.unwindCarryForward({ organizationId: orgId, lineId: bf.id });
  ck('A5 undoing puts the balance back exactly', (await owed(orgId, src.id)) === before, `got ${await owed(orgId, src.id)}`);
  ck('A6 and the source is owed again', (await statusOf(src.id)) === 'ISSUED', `got ${await statusOf(src.id)}`);
  const goneLines = await prisma.invoiceLine.count({ where: { invoiceId: target.id, kind: 'OVERDUE_CARRYFORWARD' } });
  ck('A7 the b/f line is off the target', goneLines === 0);
  ck('A8 the books still balance', await trialBalanced(orgId));

  // It can be carried again — into the right month this time.
  const target2 = await billing.carryForward({ organizationId: orgId, invoiceId: src.id, targetPeriod: '2019-02' });
  const bf2 = (await prisma.invoiceLine.findMany({ where: { invoiceId: target2.id, kind: 'OVERDUE_CARRYFORWARD' } }))[0];
  ck('A9 and it can then be carried into the right month', Number(bf2?.amount) === 8000, `got ${bf2?.amount}`);

  console.log('');
  console.log('B. Once the target is issued, unwinding is refused');
  await issueInvoice(deps, orgId, target2.id);
  let refused = '';
  try {
    await billing.unwindCarryForward({ organizationId: orgId, lineId: bf2.id });
  } catch (e) {
    refused = e instanceof Error ? e.message : String(e);
  }
  ck('B1 refused, pointing at void instead', refused.includes('void it instead'), `got "${refused}"`);
  ck('B2 and nothing moved', (await owed(orgId, target2.id)) === '8000.00');

  console.log('');
  console.log('C. A deposit applied to the wrong invoice can be taken back');
  const other = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2019-03' });
  await issueInvoice(deps, orgId, other.id);
  const dep = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: lease.id, amount: '5000' });
  const heldBefore = await held(orgId, dep.id);
  const owedBefore = await owed(orgId, other.id);
  ck('C1 the deposit holds its full amount', heldBefore === '5000.00', `got ${heldBefore}`);

  await deposits.apply({ organizationId: orgId, depositId: dep.id, invoiceId: other.id, amount: '3000' });
  ck('C2 applying reduces the deposit', (await held(orgId, dep.id)) === '2000.00', `got ${await held(orgId, dep.id)}`);
  ck('C3 and the invoice', (await owed(orgId, other.id)) === '5000.00', `got ${await owed(orgId, other.id)}`);
  ck('C4 the deposit reads partly applied', (await prisma.deposit.findUniqueOrThrow({ where: { id: dep.id }, select: { status: true } })).status === 'PARTIALLY_APPLIED');

  const alloc = await prisma.depositAllocation.findFirstOrThrow({ where: { depositId: dep.id }, select: { id: true } });
  await deposits.unapply({ organizationId: orgId, allocationId: alloc.id });
  ck('C5 undoing restores the deposit exactly', (await held(orgId, dep.id)) === heldBefore, `got ${await held(orgId, dep.id)}`);
  ck('C6 and the invoice exactly', (await owed(orgId, other.id)) === owedBefore, `got ${await owed(orgId, other.id)}`);
  ck('C7 the deposit is fully held again', (await prisma.deposit.findUniqueOrThrow({ where: { id: dep.id }, select: { status: true } })).status === 'HELD');
  ck('C8 the allocation is gone', (await prisma.depositAllocation.count({ where: { depositId: dep.id } })) === 0);
  ck('C9 the books still balance', await trialBalanced(orgId));

  console.log('');
  console.log('D0. Every posting records who made it');
  // JournalEntry.createdById has always existed and LedgerService has always
  // threaded it — but only 2 of 12 call sites filled it in, so the ledger could
  // say what happened and never who. These four are the money movements.
  const actorOf = async (sourceType: JournalSourceType, sourceId: string) =>
    (await prisma.journalEntry.findFirst({ where: { sourceType, sourceId }, orderBy: { createdAt: 'desc' }, select: { createdById: true } }))?.createdById ?? null;
  const who = 'zz-undo-actor';
  const inv2 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2019-07' });
  await issueInvoice(deps, orgId, inv2.id, who);
  ck('D0a issuing a debit note', (await actorOf('INVOICE', inv2.id)) === who, `got ${await actorOf('INVOICE', inv2.id)}`);
  const dep2 = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: lease.id, amount: '400', receivedByUserId: who });
  ck('D0b receiving a deposit', (await actorOf('DEPOSIT', dep2.id)) === who, `got ${await actorOf('DEPOSIT', dep2.id)}`);
  await deposits.apply({ organizationId: orgId, depositId: dep2.id, invoiceId: inv2.id, amount: '100', appliedByUserId: who });
  ck('D0c applying it', (await actorOf('DEPOSIT_ALLOCATION', dep2.id)) === who, `got ${await actorOf('DEPOSIT_ALLOCATION', dep2.id)}`);
  const alloc0 = await prisma.depositAllocation.findFirstOrThrow({ where: { depositId: dep2.id }, select: { id: true } });
  await deposits.unapply({ organizationId: orgId, allocationId: alloc0.id, reversedByUserId: who });
  ck('D0d and undoing it', (await actorOf('DEPOSIT_ALLOCATION', dep2.id)) === who);

  console.log('');
  console.log('D. Applying again afterwards works, so nothing is left stuck');
  await deposits.apply({ organizationId: orgId, depositId: dep.id, invoiceId: other.id, amount: '5000' });
  ck('D1 the whole deposit can now be applied', (await held(orgId, dep.id)) === '0.00', `got ${await held(orgId, dep.id)}`);
  ck('D2 the invoice takes it', (await owed(orgId, other.id)) === '3000.00', `got ${await owed(orgId, other.id)}`);
  const fullyApplied = (await prisma.deposit.findUniqueOrThrow({ where: { id: dep.id }, select: { status: true } })).status;
  ck('D3 and the deposit reads fully applied', fullyApplied === 'APPLIED', `got ${fullyApplied}`);
  const alloc2 = await prisma.depositAllocation.findFirstOrThrow({ where: { depositId: dep.id }, select: { id: true } });
  await deposits.unapply({ organizationId: orgId, allocationId: alloc2.id });
  ck('D4 and that one undoes too', (await held(orgId, dep.id)) === '5000.00', `got ${await held(orgId, dep.id)}`);
  ck('D5 books still balance after two rounds', await trialBalanced(orgId));
}

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 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 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 } } });
  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 } });
}

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 rev = entries.filter((e) => e.reversesId).map((e) => e.id);
  if (rev.length) await prisma.journalEntry.deleteMany({ where: { id: { in: rev } } });
  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); });
