import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import type { Deposit, Prisma } from '@prisma/client';
import { Decimal, sum } from '@rms/domain';
import { ApprovalService } from '../approvals/approval.service';
import { PRE_ISSUE_STATUSES } from '../billing/invoice-status';
import { leasePropertyIds, propertyIdsOf } from '../common/lease-premises';
import { NumberService } from '../common/number.service';
import { LedgerService } from '../ledger/ledger.service';
import { findSystemAccount, systemAccount } from '../ledger/system-accounts';
import { leaseBankLedgerAccount } from '../ledger/bank-accounts';
import { PrismaService } from '../prisma/prisma.service';
import { assertSettlementMethod } from '../common/settlement-method';
import { heldByDeposit } from './deposit-held';


@Injectable()
export class DepositsService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly ledger: LedgerService,
    private readonly numbers: NumberService,
    private readonly approvals: ApprovalService,
  ) {}

  private async invoiceOutstanding(tx: Prisma.TransactionClient, organizationId: string, invoiceId: string): Promise<Decimal> {
    const ar = await findSystemAccount(tx, organizationId, 'RECEIVABLE');
    if (!ar) return new Decimal(0);
    const lines = await tx.journalLine.findMany({ where: { accountId: ar.id, invoiceId } });
    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()));
    return dr.minus(cr);
  }

  /** The still-held balance of a deposit, derived from the ledger (heldByDeposit). */
  private async depositHeld(tx: Prisma.TransactionClient, organizationId: string, depositId: string): Promise<Decimal> {
    const dep = await tx.deposit.findFirst({ where: { id: depositId }, select: { sourceInvoiceId: true } });
    const held = await heldByDeposit(tx, organizationId, [{ id: depositId, sourceInvoiceId: dep?.sourceInvoiceId ?? null }]);
    return held.get(depositId) ?? new Decimal(0);
  }

  /** Receive a deposit into the held pool: DR its lease's bank / CR Deposits Held. */
  async create(input: {
    organizationId: string;
    tenantId: string;
    leaseId?: string | null;
    amount: string;
    receivedDate?: string | null;
    receivedByUserId?: string | null;
    /** A deposit receipt number the office typed; none takes the next in sequence. */
    number?: string | null;
  }): Promise<Deposit> {
    const amount = new Decimal(input.amount);
    if (amount.lte(0)) throw new BadRequestException('Amount must be positive');

    return this.prisma.$transaction(async (tx) => {
      const lease = input.leaseId
        ? await tx.lease.findFirst({ where: { id: input.leaseId, organizationId: input.organizationId }, select: { currency: true, ...leasePropertyIds } })
        : null;
      const receivedDate = input.receivedDate ? new Date(input.receivedDate) : new Date();
      const number = await this.numbers.assign(tx, input.organizationId, 'DEPOSIT', input.number, { date: receivedDate, propertyIds: lease ? propertyIdsOf(lease) : [] });
      const [bank, liability] = await Promise.all([
        leaseBankLedgerAccount(tx, input.organizationId, input.leaseId ?? null),
        systemAccount(tx, input.organizationId, 'DEPOSITS_HELD'),
      ]);
      // A deposit trades in its lease's currency (HKD when it isn't lease-linked).
      const leaseCurrency = lease?.currency ?? 'HKD';
      const deposit = await tx.deposit.create({
        data: {
          organizationId: input.organizationId,
          number,
          tenantId: input.tenantId,
          leaseId: input.leaseId ?? null,
          status: 'HELD',
          amount: amount.toFixed(2),
          currency: leaseCurrency,
          receivedDate,
        },
      });
      await this.ledger.post(tx, {
        organizationId: input.organizationId,
        entryDate: new Date(),
        sourceType: 'DEPOSIT',
        createdById: input.receivedByUserId ?? null,
        sourceId: deposit.id,
        currency: leaseCurrency,
        memo: `Deposit ${number}`,
        lines: [
          { accountId: bank.id, direction: 'DEBIT', amount: amount.toFixed(2), tenantId: input.tenantId },
          { accountId: liability.id, direction: 'CREDIT', amount: amount.toFixed(2), tenantId: input.tenantId },
        ],
      });
      return deposit;
    });
  }

  /** Apply held deposit to an invoice: DR Deposits Held / CR Accounts Receivable. */
  async apply(input: {
    organizationId: string;
    depositId: string;
    invoiceId: string;
    amount: string;
    appliedByUserId?: string | null;
  }): Promise<Deposit> {
    const amount = new Decimal(input.amount);
    if (amount.lte(0)) throw new BadRequestException('Amount must be positive');

    return this.prisma.$transaction(async (tx) => {
      // Lock the deposit row so apply()/settle() on the same deposit serialise.
      await tx.$queryRawUnsafe('SELECT id FROM deposits WHERE id = ? FOR UPDATE', input.depositId);
      const deposit = await tx.deposit.findFirst({
        where: { id: input.depositId, organizationId: input.organizationId },
      });
      if (!deposit) throw new NotFoundException('Deposit not found');
      if (deposit.status !== 'HELD' && deposit.status !== 'PARTIALLY_APPLIED') {
        throw new BadRequestException('Deposit has no remaining balance');
      }
      // Remaining held balance is derived from the ledger (2300 movements).
      const remaining = await this.depositHeld(tx, input.organizationId, deposit.id);
      if (amount.gt(remaining)) throw new BadRequestException(`Amount exceeds the deposit's remaining ${remaining.toFixed(2)}`);

      const invoice = await tx.invoice.findFirst({ where: { id: input.invoiceId, organizationId: input.organizationId } });
      if (!invoice) throw new NotFoundException('Debit note not found');
      if (invoice.currency !== deposit.currency) {
        throw new BadRequestException('The deposit and the debit note are in different currencies');
      }
      const outstanding = await this.invoiceOutstanding(tx, input.organizationId, input.invoiceId);
      if (amount.gt(outstanding)) throw new BadRequestException(`Amount exceeds the debit note's outstanding ${outstanding.toFixed(2)}`);

      const [ar, liability] = await Promise.all([
        systemAccount(tx, input.organizationId, 'RECEIVABLE'),
        systemAccount(tx, input.organizationId, 'DEPOSITS_HELD'),
      ]);

      await tx.depositAllocation.create({
        data: { depositId: deposit.id, invoiceId: invoice.id, amount: amount.toFixed(2) },
      });
      await this.ledger.post(tx, {
        organizationId: input.organizationId,
        entryDate: new Date(),
        sourceType: 'DEPOSIT_ALLOCATION',
        sourceId: deposit.id,
        currency: deposit.currency,
        createdById: input.appliedByUserId ?? null,
        memo: `Deposit ${deposit.number} → invoice`,
        lines: [
          { accountId: liability.id, direction: 'DEBIT', amount: amount.toFixed(2), tenantId: deposit.tenantId },
          { accountId: ar.id, direction: 'CREDIT', amount: amount.toFixed(2), invoiceId: invoice.id, tenantId: deposit.tenantId },
        ],
      });

      const newRemaining = remaining.minus(amount);
      const updated = await tx.deposit.update({
        where: { id: deposit.id },
        data: { status: newRemaining.lte(0) ? 'APPLIED' : 'PARTIALLY_APPLIED' },
      });

      const invOutstanding = await this.invoiceOutstanding(tx, input.organizationId, input.invoiceId);
      await tx.invoice.update({ where: { id: invoice.id }, data: { status: invOutstanding.lte(0) ? 'PAID' : 'PARTIALLY_PAID' } });

      return updated;
    });
  }

  /** Undo a manual application: put the money back in the deposit and the
   *  balance back on the invoice.
   *
   *  apply() posts DR Deposits Held / CR AR, which nothing could unwind:
   *  reverseSettlement only handles allocations a settlement created, and
   *  voidInvoice refuses any invoice with AR movement from a non-INVOICE source
   *  — which is exactly what this posted. A wrong amount or the wrong invoice,
   *  both easy from the ordinary dialog, was permanent.
   *
   *  A compensating entry rather than a reversal of the original: apply() posts
   *  against the deposit, not the allocation, so with two applications on one
   *  deposit there is no way to say which entry belongs to which. Mirroring the
   *  amounts is unambiguous and both balances are derived from the ledger
   *  anyway, so they follow.
   */
  async unapply(input: { organizationId: string; allocationId: string; reversedByUserId?: string | null }): Promise<void> {
    await this.prisma.$transaction(async (tx) => {
      const alloc = await tx.depositAllocation.findFirst({
        where: { id: input.allocationId, deposit: { organizationId: input.organizationId } },
        include: { deposit: { select: { id: true, number: true, currency: true, tenantId: true, status: true } } },
      });
      if (!alloc) throw new NotFoundException('Deposit application not found');
      if (alloc.settlementId) {
        throw new BadRequestException('This was applied by a move-out settlement; reverse the settlement instead');
      }

      // Same lock apply() and settle() take, so the three serialise on one deposit.
      await tx.$queryRawUnsafe('SELECT id FROM deposits WHERE id = ? FOR UPDATE', alloc.deposit.id);

      // Current-read write: if a settlement claimed this allocation in the
      // meantime it no longer matches, and the whole unwind rolls back.
      const claimed = await tx.depositAllocation.deleteMany({ where: { id: alloc.id, settlementId: null } });
      if (claimed.count !== 1) throw new BadRequestException('This application has already been changed; reload and try again');

      const [ar, liability] = await Promise.all([
        systemAccount(tx, input.organizationId, 'RECEIVABLE'),
        systemAccount(tx, input.organizationId, 'DEPOSITS_HELD'),
      ]);
      const amount = new Decimal(alloc.amount.toString());
      await this.ledger.post(tx, {
        organizationId: input.organizationId,
        entryDate: new Date(),
        // Same sourceType and sourceId as the application, so the deposit's
        // derived held balance counts this back in.
        sourceType: 'DEPOSIT_ALLOCATION',
        sourceId: alloc.deposit.id,
        createdById: input.reversedByUserId ?? null,
        currency: alloc.deposit.currency,
        memo: `Deposit ${alloc.deposit.number} application undone`,
        lines: [
          { accountId: ar.id, direction: 'DEBIT', amount: amount.toFixed(2), invoiceId: alloc.invoiceId, tenantId: alloc.deposit.tenantId },
          { accountId: liability.id, direction: 'CREDIT', amount: amount.toFixed(2), tenantId: alloc.deposit.tenantId },
        ],
      });

      // Both ends re-derive from the ledger rather than being adjusted by hand.
      const inv = await tx.invoice.findFirst({
        where: { id: alloc.invoiceId, organizationId: input.organizationId },
        include: { lines: { select: { amount: true } } },
      });
      if (inv && inv.status !== 'VOID' && !PRE_ISSUE_STATUSES.includes(inv.status)) {
        const outstanding = await this.invoiceOutstanding(tx, input.organizationId, inv.id);
        const total = sum(inv.lines.map((l) => l.amount.toString()));
        const status = outstanding.lte(0) ? 'PAID' : outstanding.gte(total) ? 'ISSUED' : 'PARTIALLY_PAID';
        await tx.invoice.update({ where: { id: inv.id }, data: { status } });
      }

      const remaining = await tx.depositAllocation.count({ where: { depositId: alloc.deposit.id } });
      await tx.deposit.updateMany({
        where: { id: alloc.deposit.id, status: { in: ['HELD', 'PARTIALLY_APPLIED', 'APPLIED'] } },
        data: { status: remaining > 0 ? 'PARTIALLY_APPLIED' : 'HELD' },
      });
    });
  }

  /** Data for the settlement screen: held balance, the tenant's outstanding
   * invoices (for arrears deductions) and charge types (for damage/cleaning). */
  async settlementData(organizationId: string, depositId: string) {
    const deposit = await this.prisma.deposit.findFirst({
      where: { id: depositId, organizationId },
      include: { tenant: { select: { name: true } }, lease: { select: { id: true, reference: true } } },
    });
    if (!deposit) return null;
    const tx = this.prisma as unknown as Prisma.TransactionClient;
    const held = await this.depositHeld(tx, organizationId, depositId);

    // Arrears can only be deducted in the deposit's own currency (settle enforces
    // the same), so only offer same-currency invoices.
    const invoices = await this.prisma.invoice.findMany({
      where: { organizationId, lease: { tenantId: deposit.tenantId }, currency: deposit.currency, status: { in: ['ISSUED', 'PARTIALLY_PAID'] } },
      orderBy: { dueDate: 'asc' },
      select: { id: true, number: true, billingPeriod: true },
    });
    const outstandingInvoices: { id: string; number: string | null; billingPeriod: string; outstanding: string }[] = [];
    for (const inv of invoices) {
      const o = await this.invoiceOutstanding(tx, organizationId, inv.id);
      if (o.gt(0)) outstandingInvoices.push({ id: inv.id, number: inv.number, billingPeriod: inv.billingPeriod, outstanding: o.toFixed(2) });
    }
    const chargeTypes = await this.prisma.chargeType.findMany({
      where: { organizationId, isActive: true },
      orderBy: { sortOrder: 'asc' },
      select: { id: true, nameEn: true },
    });
    return {
      depositNumber: deposit.number,
      tenantName: deposit.tenant.name,
      leaseId: deposit.lease?.id ?? null,
      leaseRef: deposit.lease?.reference ?? null,
      status: deposit.status,
      held: held.toFixed(2),
      outstandingInvoices,
      chargeTypes,
    };
  }

  async getSettlement(organizationId: string, depositId: string) {
    const s = await this.prisma.depositSettlement.findFirst({
      where: { depositId, organizationId },
      orderBy: { createdAt: 'desc' },
      include: {
        lines: true,
        refundMethod: { select: { nameEn: true, nameZh: true } },
        deposit: { select: { number: true, currency: true, tenant: { select: { name: true, nameZh: true } }, lease: { select: { reference: true } } } },
      },
    });
    if (!s) return null;
    return {
      depositNumber: s.deposit.number,
      currency: s.deposit.currency,
      tenantName: s.deposit.tenant?.name ?? '',
      tenantNameZh: s.deposit.tenant?.nameZh ?? null,
      leaseRef: s.deposit.lease?.reference ?? null,
      heldAmount: s.heldAmount.toFixed(2),
      refundAmount: s.refundAmount.toFixed(2),
      note: s.note,
      createdAt: s.createdAt,
      refundedAt: s.refundedAt,
      refundMethodEn: s.refundMethod?.nameEn ?? null,
      refundMethodZh: s.refundMethod?.nameZh ?? null,
      refundReference: s.refundReference,
      lines: s.lines.map((l) => ({ kind: l.kind, description: l.description, amount: l.amount.toFixed(2) })),
    };
  }

  /** Deposits still held (HELD/PARTIALLY_APPLIED) on a lease whose term is over
   * (ENDED/TERMINATED) — money the org owes back but hasn't settled yet. Held is
   * derived from the ledger and only positive balances are returned, so a tenant's
   * deposit is never silently forgotten after move-out. */
  async awaitingSettlement(organizationId: string) {
    const now = new Date();
    const deposits = await this.prisma.deposit.findMany({
      where: {
        organizationId,
        status: { in: ['HELD', 'PARTIALLY_APPLIED'] },
        lease: {
          OR: [
            { status: { in: ['ENDED', 'TERMINATED'] } },
            // A lease whose term has passed but whose stored status the nightly
            // job hasn't flipped yet is over in every way that matters here —
            // the same predicate the lease list derives its display status from.
            { status: 'ACTIVE', endDate: { lt: now } },
          ],
        },
      },
      orderBy: { lease: { endDate: 'asc' } },
      include: { tenant: { select: { name: true } }, lease: { select: { reference: true, endDate: true, terminatedAt: true } } },
    });
    const tx = this.prisma as unknown as Prisma.TransactionClient;
    const out: { id: string; number: string; tenantName: string; leaseRef: string | null; endDate: Date | null; held: string; currency: string }[] = [];
    for (const d of deposits) {
      const held = await this.depositHeld(tx, organizationId, d.id);
      if (held.gt(0)) {
        out.push({
          id: d.id,
          number: d.number,
          tenantName: d.tenant.name,
          leaseRef: d.lease?.reference ?? null,
          // The day the tenancy actually stopped — the termination date when it
          // was cut short, otherwise the contracted end.
          endDate: d.lease ? d.lease.terminatedAt ?? d.lease.endDate : null,
          held: held.toFixed(2),
          currency: d.currency,
        });
      }
    }
    return out;
  }

  /** Deposits still carrying a balance on one lease — what a move-out has to
   * settle. Held is derived from the ledger, never read from a stored figure. */
  async heldForLease(organizationId: string, leaseId: string) {
    const rows = await this.prisma.deposit.findMany({
      where: { organizationId, leaseId, status: { in: ['HELD', 'PARTIALLY_APPLIED'] } },
      orderBy: { number: 'asc' },
      select: { id: true, number: true, currency: true },
    });
    const tx = this.prisma as unknown as Prisma.TransactionClient;
    const out: { id: string; number: string; currency: string; held: string }[] = [];
    for (const d of rows) {
      const held = await this.depositHeld(tx, organizationId, d.id);
      if (held.gt(0)) out.push({ id: d.id, number: d.number, currency: d.currency, held: held.toFixed(2) });
    }
    return out;
  }

  /** Move-out settlement: in one balanced entry, deduct arrears (→AR) and
   * damage/cleaning charges (→each charge type's GL), then refund the remainder
   * (→Bank), draining the held deposit to zero. Concurrency-guarded so a deposit
   * can only be settled once. Produces an itemised statement. */
  async settle(input: {
    organizationId: string;
    depositId: string;
    arrears?: { invoiceId: string; amount: string }[];
    charges?: { description: string; chargeTypeId: string; amount: string }[];
    note?: string | null;
    settledByUserId?: string | null;
  }): Promise<{ settlementId: string; refundAmount: string }> {
    return this.prisma.$transaction(async (tx) => {
      // Lock the deposit row first, so a concurrent apply()/settle() serialises
      // and `held` is read against a stable balance (no over-refund race).
      await tx.$queryRawUnsafe('SELECT id FROM deposits WHERE id = ? FOR UPDATE', input.depositId);
      const deposit = await tx.deposit.findFirst({ where: { id: input.depositId, organizationId: input.organizationId } });
      if (!deposit) throw new NotFoundException('Deposit not found');
      if (deposit.status !== 'HELD' && deposit.status !== 'PARTIALLY_APPLIED') {
        throw new BadRequestException('This deposit is not open for settlement');
      }
      const held = await this.depositHeld(tx, input.organizationId, deposit.id);
      if (held.lte(0)) throw new BadRequestException('This deposit has no held balance to settle');

      // Compare-and-swap: only one settlement can win. If a concurrent settle
      // already closed it, count is 0 → throw → the whole transaction rolls back.
      const claim = await tx.deposit.updateMany({
        where: { id: deposit.id, status: { in: ['HELD', 'PARTIALLY_APPLIED'] } },
        data: { status: 'SETTLED' },
      });
      if (claim.count !== 1) throw new BadRequestException('This deposit was already settled');

      const arrears = input.arrears ?? [];
      const charges = input.charges ?? [];
      const arrearsIds = arrears.map((a) => a.invoiceId);
      if (new Set(arrearsIds).size !== arrearsIds.length) {
        throw new BadRequestException('List each arrears debit note only once — combine the amounts');
      }
      for (const x of [...arrears, ...charges]) {
        if (new Decimal(x.amount).lte(0)) throw new BadRequestException('Deduction amounts must be positive');
      }
      const deductions = sum([...arrears, ...charges].map((x) => x.amount));
      if (deductions.gt(held)) throw new BadRequestException(`Deductions ${deductions.toFixed(2)} exceed the held balance ${held.toFixed(2)}`);
      const refund = held.minus(deductions);

      const [ar, liability, refundsPayable] = await Promise.all([
        systemAccount(tx, input.organizationId, 'RECEIVABLE'),
        systemAccount(tx, input.organizationId, 'DEPOSITS_HELD'),
        systemAccount(tx, input.organizationId, 'REFUNDS_PAYABLE'),
      ]);

      const ledgerLines: Array<{ accountId: string; direction: 'DEBIT' | 'CREDIT'; amount: string; tenantId?: string; invoiceId?: string }> = [];
      const stmtLines: Array<{ kind: string; description: string; amount: string; invoiceId?: string | null; chargeTypeId?: string | null }> = [];
      const arrearsAllocationIds: string[] = [];

      // Arrears: DR Deposits Held / CR Accounts Receivable (per invoice).
      for (const a of arrears) {
        const amt = new Decimal(a.amount);
        const invoice = await tx.invoice.findFirst({
          where: { id: a.invoiceId, organizationId: input.organizationId, lease: { tenantId: deposit.tenantId } },
        });
        if (!invoice) throw new NotFoundException("Arrears debit note not found for this deposit's tenant");
        if (invoice.currency !== deposit.currency) {
          throw new BadRequestException(`Arrears debit note ${invoice.number ?? ''} is in a different currency from the deposit`);
        }
        const outstanding = await this.invoiceOutstanding(tx, input.organizationId, a.invoiceId);
        if (amt.gt(outstanding)) throw new BadRequestException(`Arrears for ${invoice.number ?? ''} exceed its outstanding ${outstanding.toFixed(2)}`);
        const alloc = await tx.depositAllocation.create({ data: { depositId: deposit.id, invoiceId: invoice.id, amount: amt.toFixed(2) } });
        arrearsAllocationIds.push(alloc.id);
        ledgerLines.push({ accountId: liability.id, direction: 'DEBIT', amount: amt.toFixed(2), tenantId: deposit.tenantId });
        ledgerLines.push({ accountId: ar.id, direction: 'CREDIT', amount: amt.toFixed(2), invoiceId: invoice.id, tenantId: deposit.tenantId });
        stmtLines.push({ kind: 'ARREARS', description: `Arrears: ${invoice.number ?? invoice.billingPeriod}`, amount: amt.toFixed(2), invoiceId: invoice.id });
      }

      // Charges: DR Deposits Held / CR the charge type's GL account.
      for (const c of charges) {
        const amt = new Decimal(c.amount);
        const ct = await tx.chargeType.findFirst({ where: { id: c.chargeTypeId, organizationId: input.organizationId, isActive: true }, include: { glAccount: true } });
        if (!ct || !ct.glAccount) throw new BadRequestException('Each deduction needs a charge type with a GL account');
        ledgerLines.push({ accountId: liability.id, direction: 'DEBIT', amount: amt.toFixed(2), tenantId: deposit.tenantId });
        ledgerLines.push({ accountId: ct.glAccount.id, direction: 'CREDIT', amount: amt.toFixed(2), tenantId: deposit.tenantId });
        stmtLines.push({ kind: 'CHARGE', description: c.description, amount: amt.toFixed(2), chargeTypeId: ct.id });
      }

      // Refund the remainder: DR Deposits Held / CR Refunds Payable. This drains
      // the held deposit but parks the cash as a payable — the actual payout to
      // the tenant (DR Refunds Payable / CR Bank) happens in disburseRefund.
      if (refund.gt(0)) {
        ledgerLines.push({ accountId: liability.id, direction: 'DEBIT', amount: refund.toFixed(2), tenantId: deposit.tenantId });
        ledgerLines.push({ accountId: refundsPayable.id, direction: 'CREDIT', amount: refund.toFixed(2), tenantId: deposit.tenantId });
        stmtLines.push({ kind: 'REFUND', description: 'Refund to tenant', amount: refund.toFixed(2) });
      }

      const entry = await this.ledger.post(tx, {
        organizationId: input.organizationId,
        entryDate: new Date(),
        sourceType: 'DEPOSIT_ALLOCATION',
        sourceId: deposit.id,
        currency: deposit.currency,
        createdById: input.settledByUserId ?? null,
        memo: `Deposit ${deposit.number} settlement`,
        lines: ledgerLines,
      });

      for (const a of arrears) {
        const o = await this.invoiceOutstanding(tx, input.organizationId, a.invoiceId);
        await tx.invoice.update({ where: { id: a.invoiceId }, data: { status: o.lte(0) ? 'PAID' : 'PARTIALLY_PAID' } });
      }

      const settlement = await tx.depositSettlement.create({
        data: {
          organizationId: input.organizationId,
          depositId: deposit.id,
          heldAmount: held.toFixed(2),
          refundAmount: refund.toFixed(2),
          note: input.note ?? null,
          settledByUserId: input.settledByUserId ?? null,
          ledgerEntryId: entry.id,
          lines: { create: stmtLines },
        },
      });
      // Tag the arrears allocations to this settlement so a reversal can undo them.
      if (arrearsAllocationIds.length) {
        await tx.depositAllocation.updateMany({ where: { id: { in: arrearsAllocationIds } }, data: { settlementId: settlement.id } });
      }

      // Settling a deposit deliberately does NOT touch the lease. Ending a
      // tenancy is its own action (leases.terminate / the nightly expiry job),
      // so the two can never disagree on whether it ended or was terminated.

      return { settlementId: settlement.id, refundAmount: refund.toFixed(2) };
    });
  }

  /** Pay out a settled deposit's refund: DR Refunds Payable / CR Bank, recording
   * the method, reference and who authorised it, then flip the deposit to
   * REFUNDED. Opt-in approval gate (documentType DEPOSIT_REFUND) — if a workflow
   * applies, the payout is blocked until it is approved. Idempotent: a settlement
   * can only be paid once (compare-and-swap on refundedAt). */
  /** What the refund approval looks like right now, for the clerk's screen.
   *
   *  Deliberately read-only: it must NOT call gate(), which opens a round as a
   *  side effect of asking. The clerk needs to learn an approval applies before
   *  acting, not to have started one by looking. */
  async refundApprovalState(organizationId: string, depositId: string, userId: string) {
    const deposit = await this.prisma.deposit.findFirst({
      where: { id: depositId, organizationId },
      select: { id: true, currency: true },
    });
    if (!deposit) return null;
    const settlement = await this.prisma.depositSettlement.findFirst({
      where: { depositId: deposit.id, organizationId },
      orderBy: { createdAt: 'desc' },
    });
    if (!settlement) return null;

    const refund = new Decimal(settlement.refundAmount.toString());
    const base = { settlementId: settlement.id, refundAmount: refund.toFixed(2), currency: deposit.currency };
    const wf = await this.approvals.requirementFor(organizationId, 'DEPOSIT_REFUND', refund);
    // One shape either way, so the caller branches on `required` rather than on
    // which fields happen to be there.
    if (!wf) {
      return { ...base, required: false, canAct: false, workflowName: '', totalSteps: 0, current: null, rounds: [] };
    }
    const state = await this.approvals.documentState(organizationId, 'DEPOSIT_REFUND', settlement.id, userId, refund);
    // state carries its own `required`, which is the same answer — spread it
    // first so the shape stays the engine's and this only adds context.
    return { ...base, ...state, workflowName: wf.name, totalSteps: wf.steps.length };
  }

  /** Send a refund for approval — the deposit equivalent of submitting a debit
   *  note. This is what makes a rejection recoverable: submit() opens round N+1
   *  over a settled one, so a refund that was refused can be corrected and sent
   *  again, with the earlier round kept as history. gate() alone cannot do that,
   *  since it returns the latest live round forever. */
  async submitRefundForApproval(input: { organizationId: string; depositId: string }): Promise<{ workflowName: string; totalSteps: number }> {
    const deposit = await this.prisma.deposit.findFirst({
      where: { id: input.depositId, organizationId: input.organizationId },
      select: { id: true, status: true },
    });
    if (!deposit) throw new NotFoundException('Deposit not found');
    if (deposit.status !== 'SETTLED') throw new BadRequestException('Only a settled deposit can be refunded');
    const settlement = await this.prisma.depositSettlement.findFirst({
      where: { depositId: deposit.id, organizationId: input.organizationId },
      orderBy: { createdAt: 'desc' },
    });
    if (!settlement) throw new BadRequestException('This deposit has no settlement to refund');
    if (settlement.refundedAt) throw new BadRequestException('This refund has already been paid');

    // submit() hands back an already-open round rather than opening a second
    // one, so asking first is how the caller learns nothing new happened
    // instead of being told a fresh round was started.
    const already = await this.prisma.approvalInstance.findFirst({
      where: { documentType: 'DEPOSIT_REFUND', documentId: settlement.id, isComplete: false, cancelledAt: null },
      select: { id: true },
    });
    if (already) throw new BadRequestException('This refund is already awaiting approval');

    const refund = new Decimal(settlement.refundAmount.toString());
    const res = await this.approvals.submit(input.organizationId, 'DEPOSIT_REFUND', settlement.id, refund);
    if (!res.required) throw new BadRequestException('This refund does not need approval');
    return { workflowName: res.workflowName ?? '', totalSteps: res.totalSteps ?? 0 };
  }

  async disburseRefund(input: {
    organizationId: string;
    depositId: string;
    settlementMethodId?: string | null;
    reference?: string | null;
    disbursedByUserId?: string | null;
  }): Promise<{ refundAmount: string }> {
    const deposit = await this.prisma.deposit.findFirst({
      where: { id: input.depositId, organizationId: input.organizationId },
      select: { id: true, number: true, currency: true, status: true, tenantId: true, leaseId: true },
    });
    if (!deposit) throw new NotFoundException('Deposit not found');
    if (deposit.status !== 'SETTLED') throw new BadRequestException('Only a settled deposit can be refunded');
    const settlement = await this.prisma.depositSettlement.findFirst({
      where: { depositId: deposit.id, organizationId: input.organizationId },
      orderBy: { createdAt: 'desc' },
    });
    if (!settlement) throw new BadRequestException('This deposit has no settlement to refund');
    if (settlement.refundedAt) throw new BadRequestException('This refund has already been paid');
    const refund = new Decimal(settlement.refundAmount.toString());
    if (refund.lte(0)) throw new BadRequestException('This settlement has no refund to pay');

    // A cheque etc. needs its reference number. Shared, because the two receipt
    // paths did not check any of this at all.
    const methodId = await assertSettlementMethod(
      this.prisma as unknown as Prisma.TransactionClient,
      input.settlementMethodId,
      input.reference,
    );

    // Approval gate (opt-in): if an active DEPOSIT_REFUND workflow applies to this
    // amount, the money can't leave the bank until it is fully approved.
    const gate = await this.approvals.gate(input.organizationId, 'DEPOSIT_REFUND', settlement.id, refund);
    if (gate.required && gate.status === 'PENDING') {
      throw new BadRequestException(`This refund needs approval — submitted to the "${gate.workflowName}" workflow. It can be paid once approved.`);
    }
    if (gate.required && gate.status === 'REJECTED') {
      throw new BadRequestException('The approval for this refund was rejected; it cannot be paid.');
    }

    return this.prisma.$transaction(async (tx) => {
      // Compare-and-swap: only one payout can claim the unpaid settlement.
      const claim = await tx.depositSettlement.updateMany({
        where: { id: settlement.id, refundedAt: null },
        data: {
          refundedAt: new Date(),
          refundMethodId: methodId,
          refundReference: input.reference?.trim() || null,
          refundedByUserId: input.disbursedByUserId ?? null,
        },
      });
      if (claim.count !== 1) throw new BadRequestException('This refund has already been paid');

      // Paid out of the lease's collection account.
      const [payable, bank] = await Promise.all([
        systemAccount(tx, input.organizationId, 'REFUNDS_PAYABLE'),
        leaseBankLedgerAccount(tx, input.organizationId, deposit.leaseId),
      ]);
      await this.ledger.post(tx, {
        organizationId: input.organizationId,
        entryDate: new Date(),
        sourceType: 'DEPOSIT_REFUND',
        createdById: input.disbursedByUserId ?? null,
        sourceId: settlement.id,
        currency: deposit.currency,
        memo: `Deposit ${deposit.number} refund`,
        lines: [
          { accountId: payable.id, direction: 'DEBIT', amount: refund.toFixed(2), tenantId: deposit.tenantId },
          { accountId: bank.id, direction: 'CREDIT', amount: refund.toFixed(2), tenantId: deposit.tenantId },
        ],
      });
      await tx.deposit.update({ where: { id: deposit.id }, data: { status: 'REFUNDED' } });
      return { refundAmount: refund.toFixed(2) };
    });
  }

  /** Reverse a settlement that hasn't been paid out yet: a mirror journal entry
   * restores the held deposit, AR and any refund payable; the arrears invoices
   * re-open; the settlement is dropped and the deposit re-opens. Only a SETTLED
   * deposit whose refund is still unpaid can be reversed — once the refund has
   * left the bank (REFUNDED) it can't be undone here. */
  async reverseSettlement(input: { organizationId: string; depositId: string; reversedByUserId?: string | null }): Promise<void> {
    const deposit = await this.prisma.deposit.findFirst({
      where: { id: input.depositId, organizationId: input.organizationId },
      select: { id: true, number: true, status: true },
    });
    if (!deposit) throw new NotFoundException('Deposit not found');
    if (deposit.status !== 'SETTLED') throw new BadRequestException('Only a settled deposit that has not been refunded can be reversed');
    const settlement = await this.prisma.depositSettlement.findFirst({
      where: { depositId: deposit.id, organizationId: input.organizationId },
      orderBy: { createdAt: 'desc' },
    });
    if (!settlement) throw new BadRequestException('This deposit has no settlement to reverse');
    if (settlement.refundedAt) throw new BadRequestException('This refund has already been paid; it cannot be reversed');
    if (!settlement.ledgerEntryId) throw new BadRequestException('This settlement cannot be reversed');

    await this.prisma.$transaction(async (tx) => {
      // Lock the deposit row so a concurrent apply()/settle()/reverse serialises.
      await tx.$queryRawUnsafe('SELECT id FROM deposits WHERE id = ? FOR UPDATE', deposit.id);

      // Capture the arrears allocations before the settlement row (and its FK) go.
      const allocs = await tx.depositAllocation.findMany({ where: { settlementId: settlement.id }, select: { id: true, invoiceId: true } });

      // Claim the settlement atomically. deleteMany is a current-read write, so if a
      // concurrent disburseRefund已 set refundedAt (or removed it), this matches 0
      // rows and the whole reversal — including the mirror entry below — rolls back.
      // This is what stops a refund being paid out AND reversed at the same time.
      const claimed = await tx.depositSettlement.deleteMany({ where: { id: settlement.id, refundedAt: null } });
      if (claimed.count !== 1) throw new BadRequestException('This refund has already been paid; it cannot be reversed');

      // 1. Mirror the settlement's journal entry — restores Deposits Held, AR and
      //    the refund payable.
      await this.ledger.reverse(tx, {
        entryId: settlement.ledgerEntryId as string,
        entryDate: new Date(),
        memo: `Reversal of deposit ${deposit.number} settlement`,
        createdById: input.reversedByUserId ?? null,
      });

      // 2. Drop the arrears allocations this settlement created and re-open the
      //    affected invoices (their AR is restored by the reversal above).
      const invoiceIds = [...new Set(allocs.map((a) => a.invoiceId))];
      if (allocs.length) await tx.depositAllocation.deleteMany({ where: { id: { in: allocs.map((a) => a.id) } } });
      for (const invId of invoiceIds) {
        const inv = await tx.invoice.findFirst({ where: { id: invId, organizationId: input.organizationId }, include: { lines: { select: { amount: true } } } });
        if (!inv || inv.status === 'VOID' || PRE_ISSUE_STATUSES.includes(inv.status)) continue;
        const outstanding = await this.invoiceOutstanding(tx, input.organizationId, invId);
        const total = sum(inv.lines.map((l) => l.amount.toString()));
        const status = outstanding.lte(0) ? 'PAID' : outstanding.gte(total) ? 'ISSUED' : 'PARTIALLY_PAID';
        await tx.invoice.update({ where: { id: invId }, data: { status } });
      }

      // 3. Clean up any approval instance raised for this refund.
      await tx.approvalInstance.deleteMany({ where: { documentType: 'DEPOSIT_REFUND', documentId: settlement.id } });

      // 4. Re-open the deposit — CAS on SETTLED so nothing else can be clobbered.
      const remaining = await tx.depositAllocation.count({ where: { depositId: deposit.id } });
      const reopened = await tx.deposit.updateMany({ where: { id: deposit.id, status: 'SETTLED' }, data: { status: remaining > 0 ? 'PARTIALLY_APPLIED' : 'HELD' } });
      if (reopened.count !== 1) throw new BadRequestException('This deposit is no longer settled');
    });
  }
}
