/*
|--------------------------------------------------------------------------
| Paid (VedicAstro) services — insufficient wallet balance
|--------------------------------------------------------------------------
| Paid astrology calls (yearly horoscope, kundli, panchang, tarot, ...) fail
| with a body like
|   { status: false, message: "Insufficient wallet balance. ...",
|     data: { error_code: "INSUFFICIENT_BALANCE", recharge_required: true,
|             required_amount: 10, shortfall: 10, wallet_balance: 0,
|             service_code: "horoscope.yearly", service_name: "Yearly horoscope" } }
| parseInsufficientBalance() recognises that shape so every caller can offer a
| "Recharge wallet" button that pre-fills the missing amount.
*/

export interface InsufficientBalance {
  shortfall: number;
  requiredAmount: number;
  walletBalance: number;
  serviceName: string;
  message: string;
}

export function parseInsufficientBalance(body: any): InsufficientBalance | null {
  const data = body?.data;

  if (
    data?.error_code !== "INSUFFICIENT_BALANCE" &&
    !(data?.recharge_required === true && Number(data?.shortfall) > 0)
  ) {
    return null;
  }

  const required = Number(data?.required_amount) || 0;
  const balance = Number(data?.wallet_balance) || 0;
  const shortfall = Number(data?.shortfall) || Math.max(required - balance, 0);

  return {
    shortfall,
    requiredAmount: required,
    walletBalance: balance,
    serviceName: String(data?.service_name || "this service"),
    message:
      typeof body?.message === "string" && body.message
        ? body.message
        : "Insufficient wallet balance. Please recharge your wallet to continue.",
  };
}

// Where the "Recharge wallet" button goes; the price list pre-fills `amount`.
export function walletRechargeUrl(shortfall?: number): string {
  const amount = Math.ceil(Number(shortfall) || 0);

  return amount > 0
    ? `/add-wallet-money/price-list?amount=${amount}`
    : "/add-wallet-money/price-list";
}

// For the throwing kundli helpers (they signal errors by throwing).
export class InsufficientBalanceError extends Error {
  info: InsufficientBalance;

  constructor(info: InsufficientBalance) {
    super(info.message);
    this.name = "InsufficientBalanceError";
    this.info = info;
  }
}
