import { getCachedAdminCurrencies } from "@/hooks/use-admin-currency-catalog";

const DEFAULT_DECIMAL_PLACES = 2;

export function getAdminCurrencyDecimalPlaces(currencyCode: string | null | undefined): number {
  const code = currencyCode?.trim().toUpperCase();
  if (!code) {
    return DEFAULT_DECIMAL_PLACES;
  }

  const row = getCachedAdminCurrencies().find((item) => item.code === code);
  const decimals = row?.decimal_places;
  if (typeof decimals === "number" && Number.isFinite(decimals) && decimals >= 0) {
    return decimals;
  }

  return DEFAULT_DECIMAL_PLACES;
}

/** 后台列表统一：最小货币单位 → 主货币展示（默认 2 位小数，与钱包一致） */
export function formatAdminMinorUnits(
  minor: number,
  currencyCode = "NPR",
  decimalPlaces?: number,
): string {
  const resolvedDecimalPlaces =
    typeof decimalPlaces === "number" && Number.isFinite(decimalPlaces) && decimalPlaces >= 0
      ? decimalPlaces
      : getAdminCurrencyDecimalPlaces(currencyCode);
  const major = minor / 10 ** resolvedDecimalPlaces;
  return `${currencyCode} ${major.toLocaleString(undefined, {
    minimumFractionDigits: resolvedDecimalPlaces,
    maximumFractionDigits: resolvedDecimalPlaces,
  })}`;
}
