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

export interface InvoiceArState {
  /** Debits − credits on the AR account for this invoice: what's still owed. */
  outstanding: Decimal;
  /** AR debits from the invoice's own issue posting — the original charge total. */
  chargeTotal: Decimal;
}

/** Per-invoice AR position, read straight from the append-only ledger. Never a
 * stored, mutable field — the ledger is the single source of truth. */
export async function invoiceArState(
  tx: Prisma.TransactionClient,
  organizationId: string,
  invoiceId: string,
): Promise<InvoiceArState> {
  const ar = await findSystemAccount(tx, organizationId, 'RECEIVABLE');
  if (!ar) return { outstanding: new Decimal(0), chargeTotal: new Decimal(0) };
  const lines = await tx.journalLine.findMany({
    where: { accountId: ar.id, invoiceId },
    include: { entry: { select: { sourceType: true } } },
  });
  let dr = new Decimal(0);
  let cr = new Decimal(0);
  let chargeDr = new Decimal(0);
  for (const l of lines) {
    const amt = new Decimal(l.amount.toString());
    if (l.direction === 'DEBIT') {
      dr = dr.plus(amt);
      // INVOICE-source debits are the real charges; RECEIPT reversals (bounce)
      // and ADJUSTMENT transfers (carry-forward) are excluded so a bounced
      // invoice reads as fully-owed (ISSUED) rather than PARTIALLY_PAID.
      if (l.entry.sourceType === 'INVOICE') chargeDr = chargeDr.plus(amt);
    } else {
      cr = cr.plus(amt);
    }
  }
  return { outstanding: dr.minus(cr), chargeTotal: chargeDr };
}

/** Maps an AR position to a lifecycle status (never returns DRAFT/VOID). */
export function deriveInvoiceStatus(state: InvoiceArState): InvoiceStatus {
  if (state.outstanding.lte(0)) return 'PAID';
  if (state.outstanding.gte(state.chargeTotal)) return 'ISSUED';
  return 'PARTIALLY_PAID';
}
