import axios from 'axios';
import { message } from 'antd';

// 创建 axios 实例
const apiClient = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器：自动添加 Authorization 头
apiClient.interceptors.request.use(
  (config) => {
    // 从 localStorage 获取 token
    const authData = localStorage.getItem('auth-storage');
    if (authData) {
      try {
        const parsed = JSON.parse(authData);
        const token = parsed.state?.token;
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
      } catch (e) {
        // 忽略解析错误
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器：处理 401 未授权
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      // 清除登录状态并跳转登录页
      localStorage.removeItem('auth-storage');
      message.error('登录已过期，请重新登录');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export default apiClient;

// 导出常用方法
export const get = (url: string, config?: any) => apiClient.get(url, config);
export const post = (url: string, data?: any, config?: any) => apiClient.post(url, data, config);
export const put = (url: string, data?: any, config?: any) => apiClient.put(url, data, config);
export const del = (url: string, config?: any) => apiClient.delete(url, config);