/**
 * Smoke for the deposit refund disbursement flow (Phase B):
 *  - settle parks the refund in Refunds Payable (2310), deposit stays SETTLED
 *  - disburseRefund pays it out (drains 2310), deposit → REFUNDED, records method
 *  - a second payout is rejected
 *  - an opt-in DEPOSIT_REFUND approval workflow blocks the payout until approved
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/refund-smoke.ts
 */
import 'reflect-metadata';
import type { GlAccountRole } from '@prisma/client';
import { Decimal, sum } from '@rms/domain';
import { ApprovalService } from '../src/approvals/approval.service';
import { DepositsService } from '../src/deposits/deposits.service';
import { leaseBankLedgerAccount } from '../src/ledger/bank-accounts';
import { LedgerService } from '../src/ledger/ledger.service';
import { NumberService } from '../src/common/number.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { purgeSmokeLandlord, smokeLandlord } from './_smoke-company';

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

const prisma = new PrismaService();
const approvals = new ApprovalService(prisma);
const deposits = new DepositsService(prisma, new LedgerService(), new NumberService(), approvals);
let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };

async function bal(orgId: string, role: GlAccountRole): Promise<Decimal> {
  const acc = await prisma.glAccount.findFirst({ where: { organizationId: orgId, role } });
  return acc ? balOf(acc.id) : new Decimal(0);
}

/** Credits less debits on one account. */
async function balOf(accountId: string): Promise<Decimal> {
  const lines = await prisma.journalLine.findMany({ where: { accountId } });
  const cr = sum(lines.filter((l) => l.direction === 'CREDIT').map((l) => l.amount.toString()));
  const dr = sum(lines.filter((l) => l.direction === 'DEBIT').map((l) => l.amount.toString()));
  return cr.minus(dr);
}

async function purge(orgId: string) {
  await purgeSmokeLandlord(prisma, LANDLORD);
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: 'ZZ-RFND' } }, select: { id: true } });
  const ids = leases.map((l) => l.id);
  const deps = await prisma.deposit.findMany({ where: { OR: [{ leaseId: { in: ids } }, { tenant: { name: 'ZZ Rfnd Tenant' } }] }, select: { id: true } });
  const depIds = deps.map((d) => d.id);
  const settlements = await prisma.depositSettlement.findMany({ where: { depositId: { in: depIds } }, select: { id: true } });
  const setIds = settlements.map((s) => s.id);
  if (setIds.length) {
    await prisma.approvalInstance.deleteMany({ where: { documentType: 'DEPOSIT_REFUND', documentId: { in: setIds } } });
  }
  await prisma.journalLine.deleteMany({ where: { entry: { sourceId: { in: [...ids, ...depIds, ...setIds] } } } });
  await prisma.journalEntry.deleteMany({ where: { sourceId: { in: [...ids, ...depIds, ...setIds] } } });
  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: { id: { in: depIds } } });
  await prisma.leaseUnit.deleteMany({ where: { leaseId: { in: ids } } });
  await prisma.lease.deleteMany({ where: { id: { in: ids } } });
  await prisma.approvalWorkflow.deleteMany({ where: { organizationId: orgId, code: 'ZZ-RFND-WF' } });
  const props = await prisma.property.findMany({ where: { organizationId: orgId, name: 'ZZ Rfnd Property' }, select: { id: true } });
  const propIds = props.map((p) => p.id);
  if (propIds.length) {
    await prisma.unit.deleteMany({ where: { propertyId: { in: propIds } } });
    await prisma.property.deleteMany({ where: { id: { in: propIds } } });
  }
  await prisma.tenant.deleteMany({ where: { organizationId: orgId, name: 'ZZ Rfnd Tenant' } });
}

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;
  await purge(orgId);

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Rfnd Tenant' } });
  const prop = await prisma.property.create({ data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: 'ZZ Rfnd Property', units: { create: { name: 'ZZ RU1' } } }, include: { units: true } });
  const lease = await prisma.lease.create({ data: { organizationId: orgId, reference: 'ZZ-RFND-L1', tenantId: tenant.id, status: 'ENDED', currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date('2020-01-31'), depositMonths: 0, units: { create: { unitId: prop.units[0].id } } } });
  const rm = await prisma.chargeType.findFirst({ where: { organizationId: orgId, code: 'RM' } });
  const method = await prisma.settlementMethod.findFirst({ where: { isActive: true } });

  // ── A. settle → refund parked in Refunds Payable (2310) ──
  const dep = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: lease.id, amount: '20000' });
  const payableBefore = await bal(orgId, 'REFUNDS_PAYABLE');
  const settle = await deposits.settle({ organizationId: orgId, depositId: dep.id, charges: rm ? [{ description: 'Cleaning', chargeTypeId: rm.id, amount: '5000' }] : [], settledByUserId: null });
  const afterSettle = await bal(orgId, 'REFUNDS_PAYABLE');
  ck('A1 refund amount = 15000.00', settle.refundAmount === '15000.00', `got ${settle.refundAmount}`);
  ck('A2 deposit is SETTLED', (await prisma.deposit.findUniqueOrThrow({ where: { id: dep.id } })).status === 'SETTLED');
  ck('A3 Refunds Payable rose by 15000', afterSettle.minus(payableBefore).toFixed(2) === '15000.00', `delta ${afterSettle.minus(payableBefore).toFixed(2)}`);
  ck('A4 settlement not yet refunded', (await prisma.depositSettlement.findFirstOrThrow({ where: { depositId: dep.id } })).refundedAt === null);

  // ── B. disburse (no workflow) → paid out, deposit REFUNDED ──
  // Paid out of the lease's collection account's bank (ledger/bank-accounts.ts).
  const bank = await leaseBankLedgerAccount(prisma, orgId, lease.id);
  const bankBefore = await balOf(bank.id);
  await deposits.disburseRefund({ organizationId: orgId, depositId: dep.id, settlementMethodId: method?.id ?? null, reference: 'CHQ-001', disbursedByUserId: null });
  const afterPay = await bal(orgId, 'REFUNDS_PAYABLE');
  const bankAfter = await balOf(bank.id);
  const set = await prisma.depositSettlement.findFirstOrThrow({ where: { depositId: dep.id } });
  ck('B1 deposit is REFUNDED', (await prisma.deposit.findUniqueOrThrow({ where: { id: dep.id } })).status === 'REFUNDED');
  ck('B2 Refunds Payable drained back to baseline', afterPay.toFixed(2) === payableBefore.toFixed(2), `${afterPay.toFixed(2)} vs ${payableBefore.toFixed(2)}`);
  ck('B3 Bank credited (cash out) 15000', bankAfter.minus(bankBefore).toFixed(2) === '15000.00', `delta ${bankAfter.minus(bankBefore).toFixed(2)}`);
  ck('B4 settlement records refundedAt + method + reference', set.refundedAt !== null && set.refundMethodId === (method?.id ?? null) && set.refundReference === 'CHQ-001');

  // ── C. a second payout is rejected ──
  let threw = false;
  try { await deposits.disburseRefund({ organizationId: orgId, depositId: dep.id }); } catch { threw = true; }
  ck('C1 second disburse throws', threw);

  // ── D. approval gate blocks the payout until approved ──
  const staff = await prisma.user.findFirst({ where: { tenantId: null, deletedAt: null }, select: { id: true } });
  if (!staff) { console.log('  (skip D — no staff user)'); }
  else {
    const wf = await prisma.approvalWorkflow.create({
      data: { organizationId: orgId, documentType: 'DEPOSIT_REFUND', code: 'ZZ-RFND-WF', name: 'ZZ Refund Approval', minAmount: null, isActive: true,
        steps: { create: { stepOrder: 1, name: 'Manager', actorType: 'USER', actorUserId: staff.id } } },
    });
    const lease2 = await prisma.lease.create({ data: { organizationId: orgId, reference: 'ZZ-RFND-L2', tenantId: tenant.id, status: 'ENDED', currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date('2020-01-31'), depositMonths: 0, units: { create: { unitId: prop.units[0].id } } } });
    const dep2 = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: lease2.id, amount: '10000' });
    const settle2 = await deposits.settle({ organizationId: orgId, depositId: dep2.id, settledByUserId: null });

    let blocked = false;
    try { await deposits.disburseRefund({ organizationId: orgId, depositId: dep2.id }); } catch { blocked = true; }
    ck('D1 disburse blocked while approval pending', blocked);
    ck('D2 deposit still SETTLED (not paid)', (await prisma.deposit.findUniqueOrThrow({ where: { id: dep2.id } })).status === 'SETTLED');

    const state = await approvals.documentState(orgId, 'DEPOSIT_REFUND', settle2.settlementId, staff.id);
    ck('D3 a pending approval round is open', state.current !== null, JSON.stringify(state));
    await approvals.act({ organizationId: orgId, userId: staff.id, instanceId: state.current!.instanceId, action: 'APPROVE' });

    await deposits.disburseRefund({ organizationId: orgId, depositId: dep2.id, settlementMethodId: method?.id ?? null, reference: 'CHQ-002', disbursedByUserId: staff.id });
    ck('D4 after approval, deposit is REFUNDED', (await prisma.deposit.findUniqueOrThrow({ where: { id: dep2.id } })).status === 'REFUNDED');

    // ── E. a refused refund can be corrected and sent again ──
    // Before this, a rejection was terminal: gate() returns the latest live
    // round forever, so a REJECTED one blocked the payout for good and the only
    // escape was reversing the whole settlement, which hard-deletes the
    // signatures that recorded the refusal.
    const lease3 = await prisma.lease.create({ data: { organizationId: orgId, reference: 'ZZ-RFND-L3', tenantId: tenant.id, status: 'ENDED', currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date('2020-01-31'), depositMonths: 0, units: { create: { unitId: prop.units[0].id } } } });
    const dep3 = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: lease3.id, amount: '8000' });
    const settle3 = await deposits.settle({ organizationId: orgId, depositId: dep3.id, settledByUserId: null });

    // Reading the state must NOT start a round, or the clerk's notice would be
    // the thing that triggers what it is warning about.
    const before = (await deposits.refundApprovalState(orgId, dep3.id, staff.id)) as { current: unknown; rounds: unknown[]; workflowName: string };
    ck('E1 reading the state does not open a round', before.current === null && before.rounds.length === 0, JSON.stringify(before.rounds));
    ck('E2 but it does say which workflow applies', before.workflowName === 'ZZ Refund Approval', before.workflowName);

    const sent = await deposits.submitRefundForApproval({ organizationId: orgId, depositId: dep3.id });
    ck('E3 sending it opens a round', sent.workflowName === 'ZZ Refund Approval' && sent.totalSteps === 1, JSON.stringify(sent));
    let twice = '';
    try { await deposits.submitRefundForApproval({ organizationId: orgId, depositId: dep3.id }); } catch (e) { twice = e instanceof Error ? e.message : String(e); }
    ck('E4 sending it again while open is refused', twice.includes('already awaiting approval'), `got "${twice}"`);
    const afterSubmit = (await deposits.refundApprovalState(orgId, dep3.id, staff.id)) as { rounds: unknown[] };
    ck('E5 and no second round was opened', afterSubmit.rounds.length === 1, `${afterSubmit.rounds.length} rounds`);

    // The approver must have something to open — the inbox row carries the deposit.
    const inbox = await approvals.pending(orgId, staff.id);
    const row = inbox.find((r) => r.documentId === settle3.settlementId);
    ck('E6 the inbox row names the deposit it belongs to', row?.depositId === dep3.id, `got ${row?.depositId}`);
    ck('E7 and carries a human label', Boolean(row?.documentLabel), String(row?.documentLabel));

    let stillBlocked = false;
    try { await deposits.disburseRefund({ organizationId: orgId, depositId: dep3.id }); } catch { stillBlocked = true; }
    ck('E8 the payout is blocked while it is pending', stillBlocked);

    const pending3 = (await deposits.refundApprovalState(orgId, dep3.id, staff.id)) as { current: { instanceId: string } | null };
    await approvals.act({ organizationId: orgId, userId: staff.id, instanceId: pending3.current!.instanceId, action: 'REJECT', note: 'ZZ too much' });
    const rejected = (await deposits.refundApprovalState(orgId, dep3.id, staff.id)) as { current: unknown; rounds: { status: string; actions: { note: string | null }[] }[] };
    ck('E9 a rejection closes the round', rejected.current === null);
    ck('E10 recording why', rejected.rounds[0]?.actions[0]?.note === 'ZZ too much', JSON.stringify(rejected.rounds[0]?.actions));
    let refusedAfterReject = false;
    try { await deposits.disburseRefund({ organizationId: orgId, depositId: dep3.id }); } catch { refusedAfterReject = true; }
    ck('E11 and the payout stays blocked', refusedAfterReject);

    // The recovery: send it again. This is what was impossible.
    const again = await deposits.submitRefundForApproval({ organizationId: orgId, depositId: dep3.id });
    ck('E12 it can be sent again after a refusal', again.totalSteps === 1);
    const round2 = (await deposits.refundApprovalState(orgId, dep3.id, staff.id)) as { current: { instanceId: string; round: number } | null; rounds: unknown[] };
    ck('E13 as a second round, keeping the first as history', round2.current?.round === 2 && round2.rounds.length === 2, JSON.stringify(round2.rounds.length));
    await approvals.act({ organizationId: orgId, userId: staff.id, instanceId: round2.current!.instanceId, action: 'APPROVE' });
    await deposits.disburseRefund({ organizationId: orgId, depositId: dep3.id, settlementMethodId: method?.id ?? null, reference: 'CHQ-003', disbursedByUserId: staff.id });
    ck('E14 and then it pays', (await prisma.deposit.findUniqueOrThrow({ where: { id: dep3.id } })).status === 'REFUNDED');
  }
}

main().catch((e) => { fail++; console.log(`\nFATAL: ${e instanceof Error ? e.stack : e}`); }).finally(async () => {
  const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
  if (org) await purge(org.id).catch((e) => console.log('cleanup warn', e instanceof Error ? e.message : e));
  await prisma.$disconnect();
  console.log(`\n==== ${pass} passed, ${fail} failed ====`);
  process.exit(fail > 0 ? 1 : 0);
});
