import type { Prisma } from '@prisma/client';
import { Decimal } from '@rms/domain';
import { findSystemAccount } from '../ledger/system-accounts';

/**
 * What each deposit still holds, derived from the ledger: credits − debits on
 * the Deposits-Held (2300) account across the deposit's own entries (create
 * adds, apply/settlement drain). Ledger is the single source of truth, so any
 * deduction type (invoice allocation, damage charge, refund) is counted.
 *
 * An invoice-sourced deposit posts nothing itself — its held balance is the
 * linked invoice's own 2300 credit (entry.sourceId = invoice) plus this
 * deposit's applications (entry.sourceId = deposit). This avoids double-counting.
 *
 * `upTo` reads it as at a moment, for a statement; without it, as it is now.
 */
export async function heldByDeposit(
  db: Pick<Prisma.TransactionClient, 'glAccount' | 'journalLine'>,
  organizationId: string,
  deposits: readonly { id: string; sourceInvoiceId: string | null }[],
  upTo?: Date,
): Promise<Map<string, Decimal>> {
  const out = new Map<string, Decimal>();
  const liability = await findSystemAccount(db, organizationId, 'DEPOSITS_HELD');
  if (!liability || deposits.length === 0) return out;
  const depositOf = new Map<string, string>();
  for (const d of deposits) {
    depositOf.set(d.id, d.id);
    if (d.sourceInvoiceId) depositOf.set(d.sourceInvoiceId, d.id);
  }
  const lines = await db.journalLine.findMany({
    where: { accountId: liability.id, entry: { sourceId: { in: [...depositOf.keys()] }, ...(upTo ? { entryDate: { lte: upTo } } : {}) } },
    select: { direction: true, amount: true, entry: { select: { sourceId: true } } },
  });
  for (const l of lines) {
    const id = depositOf.get(l.entry.sourceId)!;
    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;
}
