/** Priority1 / 宿主 API 错误码 → 中文说明（用户可见） */
const CODE_MESSAGES: Record<string, string> = {
  UNAUTHORIZED: "未授权，请检查服务令牌是否有效",
  FORBIDDEN: "无权访问该客户或接口未开放",
  RATE_LIMITED: "请求过于频繁，请稍后再试",
  VALIDATION_FAILED: "提交参数校验未通过",
  INTERNAL_ERROR: "服务器处理失败，请稍后重试",
  QUOTE_UNAVAILABLE: "暂时无法提交 Priority1 询价，请稍后重试",
};

const TECHNICAL_EN_PATTERN =
  /client function|use client|webpack|Cannot find module|ECONNREFUSED|Prisma|REDIS_URL|Attempted to call/i;

function isTechnicalEnglish(message: string): boolean {
  return TECHNICAL_EN_PATTERN.test(message);
}

/** 将 API code + message 转为用户可读中文 */
export function resolvePriority1UserMessage(
  code?: string | null,
  message?: string | null,
): string {
  const raw = message?.trim() ?? "";

  if (raw && !isTechnicalEnglish(raw)) {
    return raw;
  }

  const codeHint =
    code && CODE_MESSAGES[code] ? CODE_MESSAGES[code] : "Priority1 询价失败，请稍后重试";

  if (raw && isTechnicalEnglish(raw)) {
    return `${codeHint}（服务配置异常，请联系管理员）`;
  }

  return codeHint;
}
