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

/** `Bearer ` 后的原始串：`dev:1`、JWT 等 */
let playerBearerPayload: string | null = null;

/**
 * 设置玩家鉴权 Token（仅作用于彩票 API 请求）。
 * 传入 `null` 或 trim 后空串则清除。
 */
export function setPlayerBearerToken(token: string | null): void {
  if (token === null || token.trim() === "") {
    playerBearerPayload = null;
    return;
  }
  const t = token.trim();
  playerBearerPayload = t.startsWith("Bearer ") ? t.slice(7).trim() : t;
}

export function getPlayerBearerTokenPayload(): string | null {
  return playerBearerPayload;
}

export function withPlayerAuthHeader(
  config: AxiosRequestConfig,
): AxiosRequestConfig {
  if (!playerBearerPayload) {
    return config;
  }
  const merged: AxiosRequestConfig = { ...config };
  const headers = AxiosHeaders.concat(
    merged.headers as Parameters<typeof AxiosHeaders.concat>[0],
  );
  headers.set("Authorization", `Bearer ${playerBearerPayload}`);
  merged.headers = headers;
  return merged;
}