import { pickActivePlayerCurrency } from "@/lib/player-currency-options";
import { usePlayerSessionStore } from "@/stores/player-session-store";
import type { PlayerMeData } from "@/types/api/player-me";
import type { WalletBalanceData } from "@/types/api/wallet-balance";

type CurrencyProfile = Pick<PlayerMeData, "default_currency"> | null | undefined;
type CurrencyBalance = Pick<WalletBalanceData, "currency_code"> | null | undefined;

/**
 * 玩家档案/环境变量层面的默认币种（不含用户在大厅的切换选择）。
 */
export function resolvePlayerCurrency(
  profile: CurrencyProfile,
  balance?: CurrencyBalance,
): string {
  const fromBalance = balance?.currency_code?.trim();
  if (fromBalance) {
    return fromBalance.toUpperCase();
  }

  const fromProfile = profile?.default_currency?.trim();
  if (fromProfile) {
    return fromProfile.toUpperCase();
  }

  const fromEnv = process.env.NEXT_PUBLIC_LOTTERY_PLAY_CURRENCY?.trim();
  if (fromEnv) {
    return fromEnv.toUpperCase();
  }

  return "NPR";
}

/**
 * 当前业务币种（含玩家在大厅切换的可下注币种）。
 * 可在非 React 上下文（轮询、WS 刷新）中调用。
 */
export function getActivePlayerCurrencyFromStore(): string {
  const { selectedCurrency, profile, currencies } = usePlayerSessionStore.getState();
  if (selectedCurrency) {
    return selectedCurrency;
  }
  return pickActivePlayerCurrency(profile, currencies, null);
}
