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

/** `Bearer ` 后的原始串：JWT 或临时凭证 */
let adminBearerPayload: string | null = null;

/** 设置管理端鉴权 Token（仅作用于 `adminHttp` / `adminRequest`） */
export function setAdminBearerToken(token: string | null): void {
  if (token === null || token.trim() === "") {
    adminBearerPayload = null;
    return;
  }
  const t = token.trim();
  adminBearerPayload = t.startsWith("Bearer ") ? t.slice(7).trim() : t;
}

export function getAdminBearerTokenPayload(): string | null {
  return adminBearerPayload;
}

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