import { message } from 'ant-design-vue';
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios';

// 创建HTTP实例
const http: HttpInstance = axios.create({
  baseURL: import.meta.env.ENV_HTTP_BASE,
  adapter: 'fetch',
  timeout: 30_000,
});
export default http;

// 添加请求拦截器
http.interceptors.request.use(
  (config) => config,
  (error) => Promise.reject(error.message),
);

// 添加响应拦截器
http.interceptors.response.use(
  (response) => {
    const res = <CommonRes>response.data;
    if (res?.success) return <never>res.data;
    const hint = res?.message ?? '未知异常';
    message.error(hint);
    return Promise.reject(hint);
  },
  (error) => {
    const hint = error.response.data?.message || error.message;
    message.error(hint ?? '未知异常');
    return Promise.reject(hint);
  },
);

type HttpInstance = Omit<AxiosInstance, 'get' | 'post'> & {
  get: <D = void>(url: string, config?: AxiosRequestConfig) => Promise<D | undefined>;
  post: <D = void, B = unknown>(url: string, body?: B, config?: AxiosRequestConfig<B>) => Promise<D | undefined>;
};

type CommonRes<T = void> = {
  code: number;
  success: boolean;
  data: T | undefined;
  message: string;
};
