export interface WalletTransferCreditContext {
  agentId: string;
  agentUsername: string;
  agentLevel: number;
  creditLimit: string;
  usedCredit: string;
  availableCredit: string;
  maxSingleDeposit: string | null;
  maxDailyDeposit: string | null;
  dailyDepositUsed: string | null;
  appliesDepositLimits: boolean;
}

export interface WalletTransferContext {
  player: {
    id: string;
    username: string;
    availableBalance: string;
    frozenBalance: string;
  };
  credit: WalletTransferCreditContext | null;
}

export function parseCreditAvailable(ctx: WalletTransferContext | null): number {
  const n = Number(ctx?.credit?.availableCredit ?? NaN);
  return Number.isFinite(n) ? Math.max(0, n) : Infinity;
}

export function parsePlayerAvailable(ctx: WalletTransferContext | null): number {
  const n = Number(ctx?.player?.availableBalance ?? NaN);
  return Number.isFinite(n) ? Math.max(0, n) : 0;
}

/** 上分金额上限：可用授信；代理端再叠加单笔/日限 */
export function depositAmountCap(ctx: WalletTransferContext | null): number | undefined {
  if (!ctx?.credit) return undefined;
  const available = parseCreditAvailable(ctx);
  if (!Number.isFinite(available)) return undefined;
  let cap = available;
  if (ctx.credit.appliesDepositLimits) {
    const single = ctx.credit.maxSingleDeposit ? Number(ctx.credit.maxSingleDeposit) : Infinity;
    if (Number.isFinite(single)) cap = Math.min(cap, single);
    if (ctx.credit.maxDailyDeposit) {
      const dailyRem =
        Number(ctx.credit.maxDailyDeposit) - Number(ctx.credit.dailyDepositUsed ?? 0);
      if (Number.isFinite(dailyRem)) cap = Math.min(cap, Math.max(0, dailyRem));
    }
  }
  if (cap <= 0) return 0;
  return cap;
}
