import axios, {
    AxiosInstance,
    AxiosRequestConfig,
    AxiosResponse,
    InternalAxiosRequestConfig
  } from "axios";
  import { v4 as uuidv4 } from 'uuid';
  import SafeStorage, { AppStorageKey } from "@/utils/safeStorage";

  console.log('import.meta.env.VITE_API_BASE_UR:', import.meta.env.VITE_API_BASE_URL)
  // 1. 创建axios实例
  const instance: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    timeout: 10000,
    headers: {
      "Content-Type": "application/json",
      "Workspace": import.meta.env.VITE_APP_WORKSPACE,
      "Request-Id": uuidv4(),
    },
  });
  
  // 2. 请求拦截器
  instance.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      // 添加认证token（示例）
      const token = SafeStorage.get(AppStorageKey.TOKEN);
      if (token) {
        config.headers.Authorization = token as string;
      }
      return config;
    },
    (error) => Promise.reject(error)
  );
  
  // 3. 响应拦截器
  instance.interceptors.response.use(
    (response: AxiosResponse) => {
      // 统一处理响应数据格式[2](@ref)
      if (response.data.status === 401) {
        // token过期处理
        SafeStorage.clearAppStorage();
        window.location.href = "/auth/login";
      }
      return response.data; // 直接返回核心数据[1](@ref)
    },
    (error) => {
      if (error?.response?.data?.error === 'Token has expired') {
        // token过期处理
        SafeStorage.clearAppStorage();
        window.location.href = "/auth/login";
      }
      // 统一错误处理
      console.error("API Error:", error.message);
      return Promise.reject(error);
    }
  );
  
  // 4. 封装核心请求方法
  interface RequestConfig extends AxiosRequestConfig {
    data?: unknown;
    needWorkspace?: boolean;
  }
  
export const request = {
  get<T = any>(url: string, config?: RequestConfig): Promise<T> {
    return instance.get(url, config);
  },
  post<T = any>(url: string, data = {}, config?: RequestConfig): Promise<T> {
    let params: any
    if (config?.needWorkspace) {
      params = { workspace: import.meta.env.VITE_APP_WORKSPACE, ...data };
    } else {
      params = data;
    }
    return instance.post(url, params, config);
  },
  put<T = any>(url: string, data = {}, config?: RequestConfig): Promise<T> {
    let params: any
    if (config?.needWorkspace) {
      params = { workspace: import.meta.env.VITE_APP_WORKSPACE, ...data };
    } else {
      params = data;
    }
    return instance.put(url, params, config);
  },
  delete<T = any>(url: string, config?: RequestConfig): Promise<T> {
    return instance.delete(url, config);
  },
  patch<T = any>(url: string, data = {}, config?: RequestConfig): Promise<T> {
    let params: any
    if (config?.needWorkspace) {
      params = { workspace: import.meta.env.VITE_APP_WORKSPACE, ...data };
    } else {
      params = data;
    }
    return instance.patch(url, params, config);
  }
};
  
export default instance;