import { BadRequestException, NotFoundException } from '@nestjs/common';
import type { Prisma } from '@prisma/client';
import { Decimal, sum } from '@rms/domain';
import { deriveInvoiceStatus, invoiceArState } from '../billing/invoice-ar';
import { leasePropertyIds, propertyIdsOf } from '../common/lease-premises';
import { nextNumber } from '../common/number.service';
import type { LedgerService } from '../ledger/ledger.service';
import { findSystemAccount, systemAccount } from '../ledger/system-accounts';

/*
 * A lease's credit: money its tenant paid before the debit note existed, or
 * over what a note owed — the office's "Deposit Receipts". Each one is a
 * receipt of kind DEPOSIT_RECEIPT, posted DR Bank / CR Tenant Credit
 * when approved, and drawn down onto that lease's notes and no other:
 *
 *   - as each note is issued (billing.issue), and
 *   - when the deposit receipt is approved, onto notes already open,
 *
 * so a lease never shows money owed while its own credit sits unused. The
 * oldest deposit receipt is used first, on the earliest-due note first. Each
 * drawing is an allocation on the deposit receipt with a journal entry of its
 * own (RECEIPT_ALLOCATION: DR Tenant Credit / CR AR), so one can be withdrawn
 * without touching the rest — which is what voiding a note paid this way needs.
 *
 * Whatever draws or returns credit (issuing a note, approving or bouncing a
 * payment, withdrawing a drawing) or voids a note takes the lease's row lock
 * first (lockLeases): two notes issued at once would otherwise both spend the
 * same credit.
 */

async function accounts(tx: Prisma.TransactionClient, organizationId: string) {
  const [ar, credit] = await Promise.all([systemAccount(tx, organizationId, 'RECEIVABLE'), systemAccount(tx, organizationId, 'TENANT_CREDIT')]);
  return { ar, credit };
}

/**
 * Queues the transaction behind any other on these leases. It must be the
 * transaction's FIRST statement: MariaDB's repeatable read fixes what a
 * transaction sees at its first plain read, so a lock taken after one still
 * leaves the reads that follow blind to what the transaction it waited on
 * wrote. In id order, so two transactions locking several never deadlock.
 */
export async function lockLeases(tx: Prisma.TransactionClient, leaseIds: (string | null | undefined)[]): Promise<void> {
  for (const id of [...new Set(leaseIds.filter((x): x is string => !!x))].sort()) {
    await tx.$queryRawUnsafe('SELECT id FROM leases WHERE id = ? FOR UPDATE', id);
  }
}

/** The leases a receipt moves money on: a deposit receipt's own, those of the
 *  notes a receipt pays, and those its overpaid parts are held for. All fixed
 *  when it is recorded, so they are read before the transaction that locks them. */
export async function leasesOfReceipt(db: Pick<Prisma.TransactionClient, 'receipt'>, organizationId: string, receiptId: string): Promise<string[]> {
  const r = await db.receipt.findFirst({
    where: { id: receiptId, organizationId },
    select: {
      leaseId: true,
      overpayments: { select: { leaseId: true } },
      allocations: { select: { items: { select: { invoice: { select: { leaseId: true } } } } } },
    },
  });
  if (!r) return [];
  return [r.leaseId, ...r.overpayments.map((o) => o.leaseId), ...r.allocations.flatMap((a) => a.items.map((i) => i.invoice.leaseId))].filter(
    (x): x is string => !!x,
  );
}

/** The Tenant Credit account, for posting a deposit receipt's approval. */
export async function tenantCreditAccount(tx: Prisma.TransactionClient, organizationId: string) {
  return (await accounts(tx, organizationId)).credit;
}

/** What a lease holds in credit, read from the ledger: credits less debits on
 *  Tenant Credit for it. The ledger is the truth; the deposit receipts' own
 *  remainders only say which receipt a drawing came from. */
export async function leaseCredit(tx: Prisma.TransactionClient, organizationId: string, leaseId: string): Promise<Decimal> {
  return (await creditByLease(tx, organizationId, [leaseId])).get(leaseId) ?? new Decimal(0);
}

/** `leaseCredit` for several leases at once, optionally as at a moment — what a
 *  statement prints as the money held but not yet used. */
export async function creditByLease(
  db: Pick<Prisma.TransactionClient, 'glAccount' | 'journalLine'>,
  organizationId: string,
  leaseIds: string[],
  upTo?: Date,
): Promise<Map<string, Decimal>> {
  const out = new Map<string, Decimal>();
  const credit = await findSystemAccount(db, organizationId, 'TENANT_CREDIT');
  if (!credit || leaseIds.length === 0) return out;
  const lines = await db.journalLine.findMany({
    where: { accountId: credit.id, leaseId: { in: leaseIds }, ...(upTo ? { entry: { entryDate: { lte: upTo } } } : {}) },
    select: { leaseId: true, direction: true, amount: true },
  });
  for (const l of lines) {
    const id = l.leaseId as string;
    const acc = out.get(id) ?? new Decimal(0);
    out.set(id, l.direction === 'CREDIT' ? acc.plus(l.amount.toString()) : acc.minus(l.amount.toString()));
  }
  return out;
}

/** What one deposit receipt has left: its amount less what has been drawn. */
export function remainingOf(receipt: { amount: Prisma.Decimal; allocations: { status: string; items: { amount: Prisma.Decimal }[] }[] }): Decimal {
  const drawn = sum(receipt.allocations.filter((a) => a.status === 'CONFIRMED').flatMap((a) => a.items.map((i) => i.amount.toString())));
  return new Decimal(receipt.amount.toString()).minus(drawn);
}

/**
 * Draws a lease's credit onto its open notes — every open note, or just the
 * ones named. Returns how many drawings were made. The caller has locked the
 * lease (lockLeases).
 */
export async function applyLeaseCredit(
  tx: Prisma.TransactionClient,
  ledger: LedgerService,
  organizationId: string,
  leaseId: string,
  opts: { invoiceIds?: string[]; createdById?: string | null } = {},
): Promise<number> {
  const receipts = await tx.receipt.findMany({
    where: { organizationId, leaseId, kind: 'DEPOSIT_RECEIPT', status: 'APPROVED' },
    orderBy: [{ receivedDate: 'asc' }, { createdAt: 'asc' }],
    include: { allocations: { include: { items: true } } },
  });
  const sources = receipts.map((r) => ({ receipt: r, left: remainingOf(r) })).filter((s) => s.left.gt(0));
  if (sources.length === 0) return 0;

  const notes = await tx.invoice.findMany({
    where: {
      organizationId,
      leaseId,
      status: { in: ['ISSUED', 'PARTIALLY_PAID'] },
      ...(opts.invoiceIds ? { id: { in: opts.invoiceIds } } : {}),
    },
    orderBy: [{ dueDate: 'asc' }, { issueDate: 'asc' }],
    select: { id: true, number: true, currency: true },
  });
  if (notes.length === 0) return 0;

  const { ar, credit } = await accounts(tx, organizationId);
  // Never draw more than the ledger says the lease holds, whatever the receipts'
  // own arithmetic says — the two only disagree if something went wrong, and
  // then the ledger is the one to believe.
  let available = await leaseCredit(tx, organizationId, leaseId);
  const lease = await tx.lease.findFirstOrThrow({ where: { id: leaseId }, select: { tenantId: true } });
  let made = 0;
  const paid: string[] = [];

  for (const note of notes) {
    let owed = (await invoiceArState(tx, organizationId, note.id)).outstanding;
    for (const src of sources) {
      if (owed.lte(0) || available.lte(0)) break;
      if (src.left.lte(0) || src.receipt.currency !== note.currency) continue;
      const take = Decimal.min(owed, src.left, available);
      const allocation = await tx.receiptAllocation.create({
        data: { receiptId: src.receipt.id, status: 'CONFIRMED', items: { create: { invoiceId: note.id, amount: take.toFixed(2) } } },
      });
      await ledger.post(tx, {
        organizationId,
        entryDate: new Date(),
        sourceType: 'RECEIPT_ALLOCATION',
        sourceId: allocation.id,
        createdById: opts.createdById ?? null,
        currency: note.currency,
        memo: `Deposit receipt ${src.receipt.number} applied to ${note.number ?? note.id}`,
        lines: [
          { accountId: credit.id, direction: 'DEBIT', amount: take.toFixed(2), leaseId, tenantId: lease.tenantId },
          { accountId: ar.id, direction: 'CREDIT', amount: take.toFixed(2), invoiceId: note.id, leaseId, tenantId: lease.tenantId },
        ],
      });
      src.left = src.left.minus(take);
      owed = owed.minus(take);
      available = available.minus(take);
      made++;
    }
    const state = await invoiceArState(tx, organizationId, note.id);
    const status = deriveInvoiceStatus(state);
    await tx.invoice.update({ where: { id: note.id }, data: { status } });
    if (status === 'PAID') paid.push(note.id);
  }

  // A note paid this way that carried deposit charges has handed over a security
  // deposit, exactly as if a receipt had paid it.
  await raiseManagedDeposits(tx, organizationId, paid);
  return made;
}

/** Takes one drawing back off its note: the entry reversed, the allocation
 *  void, the note re-opened by that much and the credit back on the lease. */
export async function withdrawCredit(
  tx: Prisma.TransactionClient,
  ledger: LedgerService,
  organizationId: string,
  allocationId: string,
  createdById?: string | null,
): Promise<{ invoiceId: string; leaseId: string }> {
  const allocation = await tx.receiptAllocation.findFirst({
    where: { id: allocationId, receipt: { organizationId, kind: 'DEPOSIT_RECEIPT' } },
    include: { items: true, receipt: { select: { number: true, leaseId: true } } },
  });
  if (!allocation) throw new NotFoundException('Deposit receipt application not found');
  const claim = await tx.receiptAllocation.updateMany({ where: { id: allocationId, status: 'CONFIRMED' }, data: { status: 'VOID' } });
  if (claim.count !== 1) throw new BadRequestException('This application has already been withdrawn');
  const entry = await tx.journalEntry.findFirst({ where: { organizationId, sourceType: 'RECEIPT_ALLOCATION', sourceId: allocationId, reversesId: null } });
  if (!entry) throw new BadRequestException('No ledger posting found for this application');

  const invoiceId = allocation.items[0].invoiceId;
  // A security deposit raised because this drawing paid the note off goes with
  // it — refused if it has since been used, exactly as a bounced receipt is.
  await voidManagedDeposits(tx, organizationId, [invoiceId]);
  await ledger.reverse(tx, { entryId: entry.id, entryDate: new Date(), memo: `Withdrawn: deposit receipt ${allocation.receipt.number}`, createdById: createdById ?? null });
  const state = await invoiceArState(tx, organizationId, invoiceId);
  await tx.invoice.update({ where: { id: invoiceId }, data: { status: deriveInvoiceStatus(state) } });
  return { invoiceId, leaseId: allocation.receipt.leaseId! };
}

/**
 * Raises a managed security deposit for each of these notes that is now fully
 * PAID and carries deposit-category charges. It posts NOTHING to the ledger —
 * the note's issue already credited Deposits Held (2300), and the deposit's
 * held balance reads that credit through sourceInvoiceId, so the liability is
 * never counted twice. Whatever paid the note — a receipt or a deposit
 * receipt's credit — the tenant has now handed the deposit over.
 */
export async function raiseManagedDeposits(tx: Prisma.TransactionClient, organizationId: string, invoiceIds: string[]): Promise<void> {
  for (const invId of [...new Set(invoiceIds)]) {
    const inv = await tx.invoice.findFirst({
      where: { id: invId, status: 'PAID' },
      select: {
        id: true, leaseId: true, currency: true,
        lease: { select: { tenantId: true, ...leasePropertyIds } },
        lines: { where: { chargeType: { category: 'DEPOSIT' } }, select: { amount: true } },
      },
    });
    if (!inv || inv.lines.length === 0) continue;
    const existing = await tx.deposit.findUnique({ where: { sourceInvoiceId: inv.id }, select: { id: true } });
    if (existing) continue;
    const depAmount = sum(inv.lines.map((l) => l.amount.toString()));
    if (depAmount.lte(0)) continue;
    const receivedDate = new Date();
    await tx.deposit.create({
      data: {
        organizationId,
        number: await nextNumber(tx, organizationId, 'DEPOSIT', { date: receivedDate, propertyIds: propertyIdsOf(inv.lease) }),
        tenantId: inv.lease.tenantId,
        leaseId: inv.leaseId,
        sourceInvoiceId: inv.id,
        status: 'HELD',
        amount: depAmount.toFixed(2),
        currency: inv.currency,
        receivedDate,
      },
    });
  }
}

/**
 * Undoes raiseManagedDeposits for notes whose payment is being taken back. A
 * managed deposit posts nothing of its own — its held balance is read from the
 * note's 2300 credit, which taking the payment back does not touch — so left
 * alone it would stay fully HELD, money nobody handed over, free to be applied
 * or refunded out of the bank.
 */
export async function voidManagedDeposits(tx: Prisma.TransactionClient, organizationId: string, invoiceIds: string[]): Promise<void> {
  const managed = await tx.deposit.findMany({
    where: { organizationId, sourceInvoiceId: { in: invoiceIds } },
    select: { id: true, number: true, status: true, _count: { select: { allocations: true, settlements: true } } },
  });
  for (const dep of managed) {
    // Something has already been drawn from it, so unwinding here would
    // silently undo a decision somebody made. Refuse and say what to do: the
    // whole transaction rolls back.
    if (dep.status !== 'HELD' || dep._count.allocations > 0 || dep._count.settlements > 0) {
      throw new BadRequestException(
        `Deposit ${dep.number} came from this payment and has already been used; reverse that first, then bounce the receipt`,
      );
    }
    // Void it and cut the link to the invoice, so its held balance reads zero
    // and a later re-payment of the same invoice can raise a fresh one.
    await tx.deposit.update({ where: { id: dep.id }, data: { status: 'VOID', sourceInvoiceId: null } });
  }
}
