import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import type { Currency, LeaseStatus, Prisma, Receipt } from '@prisma/client';
import { Decimal, sum } from '@rms/domain';
import { deriveInvoiceStatus, invoiceArState } from '../billing/invoice-ar';
import { leasePropertyIds, propertyIdsOf } from '../common/lease-premises';
import { NumberService } from '../common/number.service';
import { LedgerService, type LedgerLineInput } from '../ledger/ledger.service';
import { PrismaService } from '../prisma/prisma.service';
import { systemAccount } from '../ledger/system-accounts';
import { leaseBankLedgerAccount, noteBankLedgerAccounts } from '../ledger/bank-accounts';
import { assertSettlementMethod } from '../common/settlement-method';
import { applyLeaseCredit, leasesOfReceipt, lockLeases, raiseManagedDeposits, tenantCreditAccount, voidManagedDeposits, withdrawCredit } from './lease-credit';


/** A lease that can hold credit: current, or still to start. */
const CREDIT_LEASE_STATUSES: LeaseStatus[] = ['ACTIVE', 'DRAFT'];

/** The lease a deposit receipt's credit is for: one of this tenant's, current or
 *  still to start — prepaying the first month of a lease being signed is the
 *  common case. Its currency is the credit's. */
async function creditLease(tx: Prisma.TransactionClient, organizationId: string, tenantId: string, leaseId: string) {
  const lease = await tx.lease.findFirst({
    where: { id: leaseId, organizationId, tenantId, deletedAt: null, status: { in: CREDIT_LEASE_STATUSES } },
    select: { id: true, currency: true, ...leasePropertyIds },
  });
  if (!lease) throw new BadRequestException('A deposit receipt must be for a current or upcoming lease of this tenant');
  return lease;
}

export interface OpenInvoice {
  id: string;
  number: string | null;
  billingPeriod: string;
  dueDate: Date;
  currency: Currency;
  outstanding: string;
}

@Injectable()
export class PaymentsService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly ledger: LedgerService,
    private readonly numbers: NumberService,
    private readonly events: EventEmitter2,
  ) {}

  /** Emits a domain event for the notification module to (best-effort) act on.
   * Fired after the transaction commits, so a notification never affects money. */
  private async emitNotify(event: string, relatedType: string, relatedId: string, organizationId: string): Promise<void> {
    try {
      await this.events.emitAsync('notify', { event, organizationId, relatedType, relatedId });
    } catch {
      // notifications are best-effort — never surface to the caller
    }
  }

  /** The overpaid part of a receipt — one bank-in, more than its notes owe. It
   *  is held for one of the tenant's leases as a deposit receipt of its own,
   *  tied to the receipt and approved, refused and bounced with it. */
  private async holdOverpayment(tx: Prisma.TransactionClient, receipt: Receipt, amount: Decimal, leaseId: string): Promise<void> {
    if (amount.lte(0)) throw new BadRequestException('Amount must be positive');
    const lease = await creditLease(tx, receipt.organizationId, receipt.tenantId, leaseId);
    if (lease.currency !== receipt.currency) {
      throw new BadRequestException('An overpayment must be held for a lease in the same currency as the payment');
    }
    await tx.receipt.create({
      data: {
        organizationId: receipt.organizationId,
        number: await this.numbers.next(tx, receipt.organizationId, 'DEPOSIT_RECEIPT', { date: receipt.receivedDate, propertyIds: propertyIdsOf(lease) }),
        tenantId: receipt.tenantId,
        kind: 'DEPOSIT_RECEIPT',
        leaseId: lease.id,
        sourceReceiptId: receipt.id,
        status: 'PENDING',
        amount: amount.toFixed(2),
        currency: lease.currency,
        receivedDate: receipt.receivedDate,
        settlementMethodId: receipt.settlementMethodId,
        reference: receipt.reference,
        note: receipt.note,
        uploadedByUserId: receipt.uploadedByUserId,
      },
    });
  }

  /** Tenant submits a payment against one of their invoices → PENDING receipt.
   *  Paid over what the note owes, the note takes what it owes and the rest is
   *  held for its lease (holdOverpayment) — the tenant states what they banked. */
  async submitReceipt(input: {
    organizationId: string;
    tenantId: string;
    invoiceId: string;
    amount: string;
    settlementMethodId?: string | null;
    reference?: string | null;
    uploadedByUserId?: string | null;
  }): Promise<Receipt> {
    return this.prisma.$transaction(async (tx) => {
      const invoice = await tx.invoice.findFirst({
        where: { id: input.invoiceId, organizationId: input.organizationId, lease: { tenantId: input.tenantId } },
        include: { lease: { select: { status: true, ...leasePropertyIds } } },
      });
      if (!invoice) throw new NotFoundException('Debit note not found');
      if (invoice.status !== 'ISSUED' && invoice.status !== 'PARTIALLY_PAID') {
        throw new BadRequestException('This debit note is not payable');
      }

      const amount = new Decimal(input.amount);
      if (amount.lte(0)) throw new BadRequestException('Amount must be positive');
      const { outstanding } = await invoiceArState(tx, input.organizationId, input.invoiceId);
      const excess = amount.minus(outstanding);
      // A lease that has ended holds no credit: the rest is the office's to sort out.
      if (excess.gt(0) && !CREDIT_LEASE_STATUSES.includes(invoice.lease.status)) {
        throw new BadRequestException(
          `This lease has ended, so no more than the outstanding balance of ${outstanding.toFixed(2)} can be paid here; please contact the office about the rest`,
        );
      }
      const paid = excess.gt(0) ? outstanding : amount;

      // Validated inside the transaction it is written in, so a method being
      // deactivated concurrently cannot slip past between the two.
      const methodId = await assertSettlementMethod(tx, input.settlementMethodId, input.reference);
      const receivedDate = new Date();
      const number = await this.numbers.next(tx, input.organizationId, 'RECEIPT', { date: receivedDate, propertyIds: propertyIdsOf(invoice.lease) });
      const receipt = await tx.receipt.create({
        data: {
          organizationId: input.organizationId,
          number,
          tenantId: input.tenantId,
          status: 'PENDING',
          amount: paid.toFixed(2),
          currency: invoice.currency,
          receivedDate,
          settlementMethodId: methodId,
          reference: input.reference ?? null,
          uploadedByUserId: input.uploadedByUserId ?? null,
          allocations: {
            create: {
              status: 'DRAFT',
              items: { create: { invoiceId: input.invoiceId, amount: paid.toFixed(2) } },
            },
          },
        },
      });
      if (excess.gt(0)) await this.holdOverpayment(tx, receipt, excess, invoice.leaseId);
      return receipt;
    });
  }

  /** Admin records one payment that settles several of a tenant's invoices at
   * once (e.g. a company paying off a stack of debit notes with one cheque).
   * Creates a PENDING multi-item receipt; it clears the ledger on approve. */
  async recordBulkPayment(input: {
    organizationId: string;
    tenantId: string;
    amount: string;
    settlementMethodId?: string | null;
    reference?: string | null;
    receivedDate?: Date;
    note?: string | null;
    uploadedByUserId?: string | null;
    allocations: { invoiceId: string; amount: string }[];
    /** A receipt number the office typed; none takes the next in sequence. */
    number?: string | null;
    /** Money paid over what the notes owe, held for one of the tenant's leases.
     *  It becomes a deposit receipt of its own, tied to this receipt. */
    overpayment?: { amount: string; leaseId: string } | null;
  }): Promise<Receipt> {
    return this.prisma.$transaction(async (tx) => {
      if (input.allocations.length === 0) throw new BadRequestException('Allocate the payment to at least one debit note');
      const total = sum(input.allocations.map((a) => a.amount));
      if (!total.equals(new Decimal(input.amount))) {
        throw new BadRequestException(`Allocations total ${total.toFixed(2)} must equal the payment amount ${new Decimal(input.amount).toFixed(2)}`);
      }

      let payCurrency: Currency | null = null;
      const propertyIds: string[] = [];
      for (const a of input.allocations) {
        const amt = new Decimal(a.amount);
        if (amt.lte(0)) throw new BadRequestException('Each allocation must be positive');
        const invoice = await tx.invoice.findFirst({
          where: { id: a.invoiceId, organizationId: input.organizationId, lease: { tenantId: input.tenantId } },
          include: { lease: { select: leasePropertyIds } },
        });
        if (!invoice) throw new BadRequestException(`Debit note not found for this tenant`);
        if (invoice.status !== 'ISSUED' && invoice.status !== 'PARTIALLY_PAID') {
          throw new BadRequestException(`Debit note ${invoice.number ?? ''} is not payable`);
        }
        // One receipt is single-currency (no FX) — refuse to mix.
        if (payCurrency && payCurrency !== invoice.currency) {
          throw new BadRequestException('All debit notes in one payment must be the same currency');
        }
        payCurrency = invoice.currency;
        propertyIds.push(...propertyIdsOf(invoice.lease));
        const { outstanding } = await invoiceArState(tx, input.organizationId, a.invoiceId);
        if (amt.gt(outstanding)) {
          throw new BadRequestException(`Allocation for ${invoice.number ?? ''} exceeds its outstanding ${outstanding.toFixed(2)}`);
        }
      }

      // Validated inside the transaction it is written in, so a method being
      // deactivated concurrently cannot slip past between the two.
      const methodId = await assertSettlementMethod(tx, input.settlementMethodId, input.reference);
      const receivedDate = input.receivedDate ?? new Date();
      const number = await this.numbers.assign(tx, input.organizationId, 'RECEIPT', input.number, { date: receivedDate, propertyIds });
      const receipt = await tx.receipt.create({
        data: {
          organizationId: input.organizationId,
          number,
          tenantId: input.tenantId,
          status: 'PENDING',
          amount: new Decimal(input.amount).toFixed(2),
          currency: payCurrency ?? 'HKD',
          receivedDate,
          settlementMethodId: methodId,
          reference: input.reference ?? null,
          note: input.note ?? null,
          uploadedByUserId: input.uploadedByUserId ?? null,
          allocations: {
            create: {
              status: 'DRAFT',
              items: { create: input.allocations.map((a) => ({ invoiceId: a.invoiceId, amount: new Decimal(a.amount).toFixed(2) })) },
            },
          },
        },
      });

      if (input.overpayment) {
        await this.holdOverpayment(tx, receipt, new Decimal(input.overpayment.amount), input.overpayment.leaseId);
      }
      return receipt;
    });
  }

  /** The office records money paid for one lease before its debit note exists
   * → a PENDING deposit receipt. Approved, it is that lease's credit, drawn
   * onto its notes as they are issued (lease-credit.ts). */
  async recordDepositReceipt(input: {
    organizationId: string;
    tenantId: string;
    leaseId: string;
    amount: string;
    settlementMethodId?: string | null;
    reference?: string | null;
    receivedDate?: Date;
    note?: string | null;
    uploadedByUserId?: string | null;
    number?: string | null;
  }): Promise<Receipt> {
    return this.prisma.$transaction(async (tx) => {
      const amount = new Decimal(input.amount);
      if (amount.lte(0)) throw new BadRequestException('Amount must be positive');
      const lease = await creditLease(tx, input.organizationId, input.tenantId, input.leaseId);
      const methodId = await assertSettlementMethod(tx, input.settlementMethodId, input.reference);
      const receivedDate = input.receivedDate ?? new Date();
      const number = await this.numbers.assign(tx, input.organizationId, 'DEPOSIT_RECEIPT', input.number, { date: receivedDate, propertyIds: propertyIdsOf(lease) });
      return tx.receipt.create({
        data: {
          organizationId: input.organizationId,
          number,
          tenantId: input.tenantId,
          kind: 'DEPOSIT_RECEIPT',
          leaseId: lease.id,
          status: 'PENDING',
          amount: amount.toFixed(2),
          currency: lease.currency,
          receivedDate,
          settlementMethodId: methodId,
          reference: input.reference ?? null,
          note: input.note ?? null,
          uploadedByUserId: input.uploadedByUserId ?? null,
        },
      });
    });
  }

  /** Posts an approved deposit receipt — DR its lease's bank / CR Tenant Credit
   * for the lease — and draws it onto any of that lease's notes already open.
   * Dated the day the money arrived, as a receipt is. */
  private async postDepositReceipt(tx: Prisma.TransactionClient, receipt: Receipt, reviewedByUserId: string | null): Promise<void> {
    const bank = await leaseBankLedgerAccount(tx, receipt.organizationId, receipt.leaseId);
    const credit = await tenantCreditAccount(tx, receipt.organizationId);
    await this.ledger.post(tx, {
      organizationId: receipt.organizationId,
      entryDate: receipt.receivedDate,
      sourceType: 'RECEIPT',
      createdById: reviewedByUserId,
      sourceId: receipt.id,
      currency: receipt.currency,
      memo: `Deposit receipt ${receipt.number}`,
      lines: [
        { accountId: bank.id, direction: 'DEBIT', amount: receipt.amount.toString(), tenantId: receipt.tenantId },
        { accountId: credit.id, direction: 'CREDIT', amount: receipt.amount.toString(), leaseId: receipt.leaseId, tenantId: receipt.tenantId },
      ],
    });
    await applyLeaseCredit(tx, this.ledger, receipt.organizationId, receipt.leaseId!, { createdById: reviewedByUserId });
  }

  /** Bounces an approved deposit receipt: every drawing of it taken back off its
   * note, then its own posting reversed. What the lease still holds from other
   * deposit receipts is drawn onto the notes this re-opened, as it would have
   * been had this one never arrived. */
  private async bounceDepositReceipt(tx: Prisma.TransactionClient, receiptId: string, reviewedByUserId: string | null): Promise<void> {
    const receipt = await tx.receipt.findFirstOrThrow({ where: { id: receiptId }, include: { allocations: true } });
    for (const a of receipt.allocations.filter((x) => x.status === 'CONFIRMED')) {
      await withdrawCredit(tx, this.ledger, receipt.organizationId, a.id, reviewedByUserId);
    }
    const entry = await tx.journalEntry.findFirst({
      where: { organizationId: receipt.organizationId, sourceType: 'RECEIPT', sourceId: receipt.id, reversesId: null },
    });
    if (!entry) throw new BadRequestException('No ledger posting found for this receipt');
    await this.ledger.reverse(tx, { entryId: entry.id, entryDate: new Date(), memo: `Bounced deposit receipt ${receipt.number}`, createdById: reviewedByUserId });
    await applyLeaseCredit(tx, this.ledger, receipt.organizationId, receipt.leaseId!, { createdById: reviewedByUserId });
  }

  /** Takes one drawing of a deposit receipt back off its note — needed before a
   * note paid this way can be voided. The credit is back on the lease and is
   * drawn again when its next note is issued. */
  async withdrawCredit(input: { organizationId: string; allocationId: string; userId?: string | null }): Promise<{ invoiceId: string }> {
    const target = await this.prisma.receiptAllocation.findFirst({
      where: { id: input.allocationId, receipt: { organizationId: input.organizationId } },
      select: { receipt: { select: { leaseId: true } } },
    });
    return this.prisma.$transaction(async (tx) => {
      // First of all: withdrawing returns credit to the lease (lease-credit.ts lockLeases).
      await lockLeases(tx, [target?.receipt.leaseId]);
      const { invoiceId } = await withdrawCredit(tx, this.ledger, input.organizationId, input.allocationId, input.userId ?? null);
      return { invoiceId };
    });
  }

  /** Admin approves → posts DR Bank / CR AR (one credit per allocated invoice)
   * and re-derives each invoice's status from the ledger. */
  async approve(input: {
    organizationId: string;
    receiptId: string;
    reviewedByUserId?: string | null;
  }): Promise<Receipt> {
    const touched = await leasesOfReceipt(this.prisma, input.organizationId, input.receiptId);
    const result = await this.prisma.$transaction(async (tx) => {
      // First of all: approving pays notes and draws credit (lease-credit.ts lockLeases).
      await lockLeases(tx, touched);
      const target = await tx.receipt.findFirst({ where: { id: input.receiptId, organizationId: input.organizationId }, select: { sourceReceiptId: true } });
      if (target?.sourceReceiptId) {
        throw new BadRequestException('This deposit receipt is the overpaid part of another receipt; approve that receipt instead');
      }
      const claim = await tx.receipt.updateMany({
        where: { id: input.receiptId, organizationId: input.organizationId, status: 'PENDING' },
        data: { status: 'APPROVED', reviewedByUserId: input.reviewedByUserId ?? null },
      });
      if (claim.count !== 1) throw new BadRequestException('Only a PENDING receipt can be approved');

      const receipt = await tx.receipt.findFirstOrThrow({
        where: { id: input.receiptId },
        include: { allocations: { include: { items: true } } },
      });

      if (receipt.kind === 'DEPOSIT_RECEIPT') {
        await this.postDepositReceipt(tx, receipt, input.reviewedByUserId ?? null);
        return tx.receipt.findFirstOrThrow({ where: { id: receipt.id } });
      }

      const ar = await systemAccount(tx, input.organizationId, 'RECEIVABLE');

      const items = receipt.allocations.flatMap((a) => a.items);
      // An invoice can be voided between submit and approve. Posting to a VOID
      // invoice would resurrect it (deriveInvoiceStatus never returns VOID) and
      // drive its AR negative — refuse rather than corrupt the ledger.
      const voided = await tx.invoice.findFirst({
        where: { id: { in: [...new Set(items.map((i) => i.invoiceId))] }, status: 'VOID' },
        select: { number: true },
      });
      if (voided) throw new BadRequestException('An debit note on this receipt was voided; the payment cannot be approved.');

      // A PENDING receipt posts nothing, so the check made when it was recorded
      // is blind to every other unposted receipt and to any deposit applied
      // since. Two receipts for the same bank-in — a tenant's declaration and
      // the office's own entry — would each look valid and both post, crediting
      // AR twice; the invoice would still read PAID and AR aging drops negative
      // balances, so nothing would ever show it. This is the only place that
      // actually credits AR, so it is the only place the check means anything.
      const byInvoice = new Map<string, Decimal>();
      for (const it of items) {
        byInvoice.set(it.invoiceId, (byInvoice.get(it.invoiceId) ?? new Decimal(0)).plus(it.amount.toString()));
      }
      for (const [invoiceId, amt] of byInvoice) {
        const { outstanding } = await invoiceArState(tx, input.organizationId, invoiceId);
        if (amt.gt(outstanding)) {
          const inv = await tx.invoice.findFirst({ where: { id: invoiceId }, select: { number: true } });
          throw new BadRequestException(`Allocation for ${inv?.number ?? ''} exceeds its outstanding ${outstanding.toFixed(2)}`);
        }
      }

      // The money went into the account each note printed, so it posts to that
      // account's bank: a payment over notes of two accounts debits both.
      const bankOf = await noteBankLedgerAccounts(tx, input.organizationId, items.map((i) => i.invoiceId));
      const debits = new Map<string, Decimal>();
      for (const it of items) {
        const bankId = bankOf.get(it.invoiceId)!.id;
        debits.set(bankId, (debits.get(bankId) ?? new Decimal(0)).plus(it.amount.toString()));
      }

      const lines: LedgerLineInput[] = [...debits].map(([accountId, amount]) => ({
        accountId,
        direction: 'DEBIT' as const,
        amount: amount.toFixed(2),
        tenantId: receipt.tenantId,
      }));
      for (const it of items) {
        lines.push({ accountId: ar.id, direction: 'CREDIT', amount: it.amount.toString(), invoiceId: it.invoiceId });
      }

      await this.ledger.post(tx, {
        organizationId: input.organizationId,
        // The day the money arrived, not the day it was keyed in — a cheque
        // banked on the 28th belongs in that month's collections even if the
        // office enters it on the 2nd. Every other path stamps receivedDate as
        // now(), so only a deliberate back-date differs.
        entryDate: receipt.receivedDate,
        sourceType: 'RECEIPT',
        createdById: input.reviewedByUserId ?? null,
        sourceId: receipt.id,
        currency: receipt.currency,
        memo: `Receipt ${receipt.number}`,
        lines,
      });

      await tx.receiptAllocation.updateMany({ where: { receiptId: receipt.id }, data: { status: 'CONFIRMED' } });

      for (const it of items) {
        const state = await invoiceArState(tx, input.organizationId, it.invoiceId);
        await tx.invoice.update({ where: { id: it.invoiceId }, data: { status: deriveInvoiceStatus(state) } });
      }

      // A note that just became fully PAID and carries deposit charges has handed
      // over a security deposit (lease-credit.ts raiseManagedDeposits).
      await raiseManagedDeposits(tx, input.organizationId, items.map((i) => i.invoiceId));

      // The overpaid part of this payment, if any, is approved with it.
      const overpaid = await tx.receipt.findMany({ where: { sourceReceiptId: receipt.id, status: 'PENDING' } });
      for (const extra of overpaid) {
        await tx.receipt.update({ where: { id: extra.id }, data: { status: 'APPROVED', reviewedByUserId: input.reviewedByUserId ?? null } });
        await this.postDepositReceipt(tx, extra, input.reviewedByUserId ?? null);
      }

      return tx.receipt.findFirstOrThrow({ where: { id: receipt.id } });
    });
    await this.emitNotify('RECEIPT_APPROVED', 'RECEIPT', result.id, input.organizationId);
    return result;
  }

  /** A previously-approved payment is dishonoured (cheque bounced). Reverses the
   * bank/AR posting with a mirror entry and re-opens the affected invoices.
   * Append-only: the original receipt and its entry are preserved. */
  async bounce(input: {
    organizationId: string;
    receiptId: string;
    reason?: string | null;
    reviewedByUserId?: string | null;
  }): Promise<Receipt> {
    const touched = await leasesOfReceipt(this.prisma, input.organizationId, input.receiptId);
    const result = await this.prisma.$transaction(async (tx) => {
      // First of all: a bounce re-opens notes and takes back credit (lease-credit.ts lockLeases).
      await lockLeases(tx, touched);
      const target = await tx.receipt.findFirst({ where: { id: input.receiptId, organizationId: input.organizationId }, select: { sourceReceiptId: true } });
      if (target?.sourceReceiptId) {
        throw new BadRequestException('This deposit receipt is the overpaid part of another receipt; bounce that receipt instead');
      }
      const claim = await tx.receipt.updateMany({
        where: { id: input.receiptId, organizationId: input.organizationId, status: 'APPROVED' },
        data: { status: 'BOUNCED', reviewedByUserId: input.reviewedByUserId ?? null },
      });
      if (claim.count !== 1) throw new BadRequestException('Only an APPROVED receipt can be bounced');
      if (input.reason) {
        await tx.receipt.update({ where: { id: input.receiptId }, data: { note: input.reason } });
      }

      const receipt = await tx.receipt.findFirstOrThrow({
        where: { id: input.receiptId },
        include: { allocations: { include: { items: true } } },
      });

      if (receipt.kind === 'DEPOSIT_RECEIPT') {
        await this.bounceDepositReceipt(tx, receipt.id, input.reviewedByUserId ?? null);
        return tx.receipt.findFirstOrThrow({ where: { id: receipt.id } });
      }

      // The overpaid part of the same cheque bounced with it.
      const overpaid = await tx.receipt.findMany({ where: { sourceReceiptId: receipt.id, status: 'APPROVED' }, select: { id: true } });
      for (const extra of overpaid) {
        await tx.receipt.update({ where: { id: extra.id }, data: { status: 'BOUNCED', reviewedByUserId: input.reviewedByUserId ?? null } });
        await this.bounceDepositReceipt(tx, extra.id, input.reviewedByUserId ?? null);
      }

      const entry = await tx.journalEntry.findFirst({
        where: { organizationId: input.organizationId, sourceType: 'RECEIPT', sourceId: receipt.id, reversesId: null },
      });
      if (!entry) throw new BadRequestException('No ledger posting found for this receipt');

      await this.ledger.reverse(tx, {
        entryId: entry.id,
        entryDate: new Date(),
        memo: `Bounced receipt ${receipt.number}`,
        createdById: input.reviewedByUserId ?? null,
      });

      await tx.receiptAllocation.updateMany({ where: { receiptId: receipt.id }, data: { status: 'VOID' } });

      const invoiceIds = [...new Set(receipt.allocations.flatMap((a) => a.items).map((it) => it.invoiceId))];

      // Approving this receipt may have auto-created a managed deposit for an
      // invoice that carried deposit charges. The cheque did not clear, so that
      // deposit is money nobody ever handed over (lease-credit.ts voidManagedDeposits).
      await voidManagedDeposits(tx, input.organizationId, invoiceIds);

      for (const invoiceId of invoiceIds) {
        const state = await invoiceArState(tx, input.organizationId, invoiceId);
        await tx.invoice.update({ where: { id: invoiceId }, data: { status: deriveInvoiceStatus(state) } });
      }

      // A re-opened note is paid from whatever credit its lease still holds, as
      // it would have been had this payment never arrived.
      const leases = await tx.invoice.findMany({ where: { id: { in: invoiceIds } }, select: { leaseId: true }, distinct: ['leaseId'] });
      for (const l of leases) {
        await applyLeaseCredit(tx, this.ledger, input.organizationId, l.leaseId, { createdById: input.reviewedByUserId ?? null });
      }

      return tx.receipt.findFirstOrThrow({ where: { id: receipt.id } });
    });
    await this.emitNotify('RECEIPT_BOUNCED', 'RECEIPT', result.id, input.organizationId);
    return result;
  }

  async reject(input: {
    organizationId: string;
    receiptId: string;
    reason?: string | null;
    reviewedByUserId?: string | null;
  }): Promise<Receipt> {
    const result = await this.prisma.$transaction(async (tx) => {
      const target = await tx.receipt.findFirst({ where: { id: input.receiptId, organizationId: input.organizationId }, select: { sourceReceiptId: true } });
      if (target?.sourceReceiptId) {
        throw new BadRequestException('This deposit receipt is the overpaid part of another receipt; reject that receipt instead');
      }
      // Its own column, not `note`: the tenant is shown this one, and being
      // told a payment was refused without being told why is the thing that
      // generates the phone call. `note` stays the office's internal remark.
      const refused = { status: 'REJECTED' as const, reviewedByUserId: input.reviewedByUserId ?? null, rejectionReason: input.reason ?? null };
      const claim = await tx.receipt.updateMany({
        where: { id: input.receiptId, organizationId: input.organizationId, status: 'PENDING' },
        data: refused,
      });
      if (claim.count !== 1) throw new BadRequestException('Only a PENDING receipt can be rejected');
      await tx.receiptAllocation.updateMany({ where: { receiptId: input.receiptId }, data: { status: 'VOID' } });
      // The overpaid part of the same payment is refused with it.
      await tx.receipt.updateMany({ where: { sourceReceiptId: input.receiptId, status: 'PENDING' }, data: refused });
      return tx.receipt.findFirstOrThrow({ where: { id: input.receiptId } });
    });
    await this.emitNotify('RECEIPT_REJECTED', 'RECEIPT', result.id, input.organizationId);
    return result;
  }

  /** A tenant's still-owed invoices with their live outstanding, for the bulk
   * payment allocator. */
  async listOpenInvoices(organizationId: string, tenantId: string): Promise<OpenInvoice[]> {
    const invoices = await this.prisma.invoice.findMany({
      where: { organizationId, lease: { tenantId }, status: { in: ['ISSUED', 'PARTIALLY_PAID'] } },
      orderBy: { dueDate: 'asc' },
      select: { id: true, number: true, billingPeriod: true, dueDate: true, currency: true },
    });
    const out: OpenInvoice[] = [];
    for (const inv of invoices) {
      const { outstanding } = await invoiceArState(this.prisma as unknown as Prisma.TransactionClient, organizationId, inv.id);
      if (outstanding.gt(0)) out.push({ ...inv, outstanding: outstanding.toFixed(2) });
    }
    return out;
  }
}
