import type { AxiosRequestConfig } from "axios";

import i18n from "@/i18n";

/** 入口/登录页：500 由页面 toast 或步骤条处理，勿全屏遮罩 */
const PUBLIC_ENTRY_PATHS = new Set(["/", "/login"]);

/** 后台静默拉取：失败不应阻断当前页 */
const BACKGROUND_URL_FRAGMENTS = ["/integration/runtime-origins"];

const TECHNICAL_ERROR_PATTERN =
  /SQLSTATE|pgsql|Connection refused|TCP\/IP|Illuminate\\|vendor\/|\.php:\d+|select\s+.+\s+from/i;

export function shouldSkipGlobalServerError(config: AxiosRequestConfig | undefined): boolean {
  if (config?.skipGlobalServerError) {
    return true;
  }

  if (typeof window !== "undefined" && PUBLIC_ENTRY_PATHS.has(window.location.pathname)) {
    return true;
  }

  const url = `${config?.url ?? ""}`;
  return BACKGROUND_URL_FRAGMENTS.some((fragment) => url.includes(fragment));
}

/** 玩家端全屏 500 仅展示友好文案，不透传 SQL / 堆栈 */
export function sanitizePlayerServerErrorMessage(raw: string | undefined): string {
  const generic = i18n.t("serverError.serverMessage", { ns: "player" });
  const trimmed = raw?.trim();
  if (!trimmed) {
    return generic;
  }
  if (TECHNICAL_ERROR_PATTERN.test(trimmed) || trimmed.length > 120) {
    return generic;
  }
  return trimmed;
}
