// *** 三方库 ***
import type { InternalAxiosRequestConfig } from "axios";
import Axios, { AxiosResponse } from "axios";
// *** 工具相关 ***
import { getLocalStorage } from "../util";
//  *** 常量相关 ***
import { USER_INFO } from "./user.constant";
// *** 类型定义文件相关 ***
import { v4 as uuid } from "uuid";
import { baseUrl } from "./baseUrl";

// 请求配置类型
interface iAxiosRequestConfig {
  baseUrl?: string; // 请求基础路径
  timeout?: number; // 请求超时时间
}
// 创建请求实例方法
const createAxiosInst = (requestConfig: iAxiosRequestConfig) => {
  const { baseUrl: baseURL = "/", timeout = 10 * 1000 } = requestConfig;
  // 创建 Axios 实例
  const tmpAxiosInstance = Axios.create({
    baseURL,
    timeout,
    withCredentials: true,
  });
  // 添加请求劫持器
  tmpAxiosInstance.interceptors.request.use(async (config: InternalAxiosRequestConfig) => {
    const nextConfig: InternalAxiosRequestConfig = { ...config };
    // 除登录接口外其余全部API都需要做认证鉴权
    if (!(nextConfig.url as string).startsWith("/api/user/account/login")) {
      // 设置角色鉴权 携带TOKEN字段，进行认证鉴权
      const userInfo: any = getLocalStorage(USER_INFO);
      nextConfig.headers.token = userInfo?.token;
      nextConfig.headers["request-id"] = uuid();
      nextConfig.headers.platform = "QIANWEN";
    }
    return nextConfig;
  });
  // 添加响应劫持器
  tmpAxiosInstance.interceptors.response.use(
    async (res: AxiosResponse<any>) => {
      return res.data;
    },
    (error: unknown) => {
      return Promise.reject(error);
    }
  );

  return tmpAxiosInstance;
};

const AxiosInstance = createAxiosInst({
  baseUrl,
  timeout: 10 * 60 * 1000, // timeout临时改成10分钟
});

export { AxiosInstance };
