import axios from 'axios';

import appClient from '#/io/tianti';
import { useUserStore } from '#/store/user';

// axios拦截器
const { reqInterceptor, resInterceptor } = appClient.getInterceptor();

const baseApiUrl = import.meta.env.VITE_BASE_API_URL;

// 创建独立实例
const instance = axios.create({
  baseURL: baseApiUrl,
});

instance.interceptors.request.use(
  (config) => config,
  (error) => Promise.reject(error),
);
instance.interceptors.request.use(
  reqInterceptor.fulfilled,
  reqInterceptor.rejected,
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 检查是否为401未授权错误
    if (response.data.code === 401) {
      const userStore = useUserStore();
      console.log('用户未授权或登录已过期，即将跳转...');
      userStore.logout();
      // 返回一个永远不会resolve的Promise，防止后续代码执行
      return new Promise(() => {});
    }
    return response;
  },
  (error) => Promise.reject(error),
);
instance.interceptors.response.use(
  resInterceptor.fulfilled,
  resInterceptor.rejected,
);

// 导出实例
export default instance;
