import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios';
import { useAuthStore } from '@/stores/auth';

interface ApiClient extends AxiosInstance {
  request<T = any, R = T>(config: AxiosRequestConfig): Promise<R>;
  get<T = any, R = T>(url: string, config?: AxiosRequestConfig): Promise<R>;
  delete<T = any, R = T>(url: string, config?: AxiosRequestConfig): Promise<R>;
  head<T = any, R = T>(url: string, config?: AxiosRequestConfig): Promise<R>;
  options<T = any, R = T>(url: string, config?: AxiosRequestConfig): Promise<R>;
  post<T = any, R = T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
  put<T = any, R = T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
  patch<T = any, R = T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
}

// 创建 Axios 实例
const apiClient = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api', // 从环境变量或默认值设置基础URL
  headers: {
    'Content-Type': 'application/json',
  },
}) as ApiClient;

// 添加请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    // 这个拦截器会在每个请求发送前执行
    const token = localStorage.getItem('token');
    if (token) {
      // 为请求头添加Authorization字段
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    return response.data;
  },
  (error) => {
    // 对响应错误做点什么
    if (error.response && error.response.status === 401) {
      // 如果是401错误，说明token无效或过期
      // 我们需要调用auth store的logout方法
      // 为了避免循环依赖，我们在函数内部获取store实例
      const authStore = useAuthStore();
      authStore.logout();
      // 在这里重定向到登录页
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export default apiClient; 
