import type { PublicCurrencyRow } from "@/types/api/currency";
import type { PlayerMeData } from "@/types/api/player-me";

import { resolvePlayerCurrency } from "@/lib/player-currency";

export function normalizeCurrencyCode(code: string | null | undefined): string | null {
  const trimmed = code?.trim();
  return trimmed ? trimmed.toUpperCase() : null;
}

export function listBettableCurrencies(currencies: PublicCurrencyRow[]): PublicCurrencyRow[] {
  return currencies.filter((row) => row.is_bettable);
}

/**
 * 解析玩家当前应使用的业务币种：持久化选择 → 玩家默认 → 首个可下注币种 → NPR 兜底。
 */
export function pickActivePlayerCurrency(
  profile: Pick<PlayerMeData, "default_currency"> | null | undefined,
  currencies: PublicCurrencyRow[],
  persistedCode: string | null,
): string {
  const bettable = listBettableCurrencies(currencies);
  const bettableCodes = bettable.map((row) => row.code);

  const persisted = normalizeCurrencyCode(persistedCode);
  if (persisted && bettableCodes.includes(persisted)) {
    return persisted;
  }

  const fromProfile = normalizeCurrencyCode(profile?.default_currency);
  if (fromProfile && bettableCodes.includes(fromProfile)) {
    return fromProfile;
  }

  if (bettable.length > 0) {
    return bettable[0].code;
  }

  return resolvePlayerCurrency(profile);
}
