import { AxiosHeaders, type AxiosRequestConfig } from "axios";

type LotteryLocale = "zh" | "en" | "ne";

let overrideLocale: LotteryLocale | null = null;

export function setLotteryRequestLocale(locale: string | null): void {
  if (locale === null) {
    overrideLocale = null;
    return;
  }
  const p = locale.trim().toLowerCase().split("-")[0] ?? "";
  overrideLocale = isLotteryLocale(p) ? p : null;
}

function isLotteryLocale(value: string): value is LotteryLocale {
  return value === "zh" || value === "en" || value === "ne";
}

/** 供前端展示文案选用语言（与请求头 `X-Locale` 逻辑一致）。 */
export function getLotteryRequestLocale(): LotteryLocale {
  return requestLocale();
}

function requestLocale(): LotteryLocale {
  if (overrideLocale) {
    return overrideLocale;
  }
  if (typeof document !== "undefined") {
    const tag = document.documentElement.lang.trim().toLowerCase();
    const primary = tag.split("-")[0] ?? tag;
    if (isLotteryLocale(primary)) {
      return primary;
    }
  }
  return "en";
}

function acceptLanguage(loc: LotteryLocale): string {
  if (loc === "zh") {
    return "zh-CN,zh;q=0.9,en;q=0.8";
  }
  if (loc === "ne") {
    return "ne,ne-NP;q=0.9,en;q=0.8";
  }
  return "en-US,en;q=0.9";
}

export function withLotteryLocaleHeaders(
  config: AxiosRequestConfig,
): AxiosRequestConfig {
  const loc = requestLocale();
  const merged: AxiosRequestConfig = { ...config };
  // Axios 的 RequestConfig.headers 类型比 concat 能接受的头对象更窄
  const headers = AxiosHeaders.concat(
    merged.headers as Parameters<typeof AxiosHeaders.concat>[0],
  );
  headers.set("X-Locale", loc);
  headers.set("Accept-Language", acceptLanguage(loc));
  merged.headers = headers;
  return merged;
}