import { isAxiosError } from "axios";

import { LotteryApiBizError } from "@/types/api/errors";

/** 钱包 / 转账 API 对用户展示的中文说明（优先业务码，其次 HTTP） */
export function formatWalletClientError(
  error: unknown,
  t?: (key: string) => string,
): string {
  if (error instanceof LotteryApiBizError) {
    const m = walletCodeMessage(error.code, t);
    if (m) return m;
    if (error.message.trim()) return error.message;
  }
  if (isAxiosError(error)) {
    if (error.response?.status === 401) {
      return msg(t, "wallet.error.401", "登录已失效，请返回重新进入。");
    }
    if (error.response?.status === 409) {
      return msg(
        t,
        "wallet.error.409",
        "转账处理中，请稍后刷新；若长时间未到账请联系客服。",
      );
    }
    if (!error.response) {
      return msg(t, "wallet.error.network", "网络异常，请检查连接后重试。");
    }
    if (error.code === "ECONNABORTED") {
      return msg(t, "wallet.error.timeout", "请求超时，请稍后重试。");
    }
  }
  if (error instanceof Error && error.message.trim()) {
    return error.message;
  }
  return msg(t, "wallet.error.fallback", "请求失败，请稍后重试。");
}

const WALLET_CODE_MESSAGES: Record<number, string> = {
  1001: "彩票钱包余额不足，请转入或减少转出金额。",
  1002: "转账处理中，请稍后在本页刷新余额；若长时间未到账请联系客服。",
  1003: "金额超出单笔或每日限额，请调整金额。",
  1004: "当前已暂停转入，请稍后再试或联系客服。",
  1005: "币种无效或未开通。",
  1006: "当前已暂停转出，请稍后再试或联系客服。",
  1007: "彩票钱包已冻结，暂无法划转。",
  1008: "金额格式不正确。",
  1009: "主站未能完成本次划转，请稍后重试。",
  1010: "请勿用同一幂等键发起不同金额的转账。",
};

function msg(
  t: ((key: string) => string) | undefined,
  key: string,
  fallback: string,
): string {
  return t?.(key) ?? fallback;
}

function walletCodeMessage(
  code: number,
  t: ((key: string) => string) | undefined,
): string | undefined {
  const fallback = WALLET_CODE_MESSAGES[code];
  if (!fallback) return undefined;
  return msg(t, `wallet.error.${code}`, fallback);
}
