/**
 * Customer side of one booking, worked out on NET amounts (client
 * 2026-10-20).
 *
 * Every price change adds a settlement line instead of editing the bill:
 * price up → an extra COLLECTION line, price down → a REFUND line. A
 * REFUND line is therefore often just a price reduction on a bill the
 * customer has not paid yet. Money is only owed back when the customer
 * has paid MORE than the net price.
 *
 *   net price    = Σ COLLECTION amount − Σ REFUND amount
 *   net received = Σ COLLECTION settled − Σ REFUND settled (paid back)
 *   outstanding  = max(net price − net received, 0)
 *   refund due   = max(net received − net price, 0)
 */
export interface CustomerTotals {
  /** Σ amount of CUSTOMER COLLECTION lines. */
  billed: number;
  /** Σ amount_settled of CUSTOMER COLLECTION lines. */
  collected: number;
  /** Σ amount of CUSTOMER REFUND lines. */
  refundLines: number;
  /** Σ amount_settled of CUSTOMER REFUND lines (money paid back). */
  refunded: number;
}

export interface CustomerPosition {
  netPrice: number;
  netReceived: number;
  outstanding: number;
  refundDue: number;
}

const EPS = 0.005;
const round2 = (n: number) => +n.toFixed(2);

export function customerPosition(t: CustomerTotals): CustomerPosition {
  const netPrice = round2(t.billed - t.refundLines);
  const netReceived = round2(t.collected - t.refunded);
  const gap = netPrice - netReceived;
  return {
    netPrice,
    netReceived,
    outstanding: gap > EPS ? round2(gap) : 0,
    refundDue: -gap > EPS ? round2(-gap) : 0,
  };
}

/** Pill state shared by the booking list and the settlement rollup. */
export type CustomerPayState = 'REFUND_DUE' | 'UNPAID' | 'PARTIAL' | 'PAID';

export function customerPayState(p: CustomerPosition): CustomerPayState {
  if (p.refundDue > EPS) return 'REFUND_DUE';
  if (p.netPrice <= EPS || p.netReceived <= EPS) return 'UNPAID';
  if (p.outstanding > EPS) return 'PARTIAL';
  return 'PAID';
}
