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

import { readPersistedPlayerBearerToken } from "@/lib/player-session";

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

function normalizeBearerPayload(token: string): string {
  const trimmed = token.trim();
  return trimmed.startsWith("Bearer ") ? trimmed.slice(7).trim() : trimmed;
}

/** 刷新后须在首个鉴权请求前恢复（子组件 useEffect 早于 HydratePlayerAuth） */
if (typeof window !== "undefined") {
  const persisted = readPersistedPlayerBearerToken();
  if (persisted?.trim()) {
    playerBearerPayload = normalizeBearerPayload(persisted);
  }
}

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

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;
}