import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message } from '@arco-design/web-react';
import { getToken } from '@/utils/auth';
import useUser from '@/hooks/user';

export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: number;
  data: T;
}

if (process.env.NEXT_API_BASE_URL) {
  axios.defaults.baseURL = process.env.NEXT_API_BASE_URL;
}

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      // config.headers.Authorization = `Bearer ${token}`
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    const res = response.data;
    if (res.code && res.code !== 200) {
      Message.error({
        content: res.msg || 'Error',
        duration: 5 * 1000
      });
      if ([-401].includes(res.code)) {
        const { logoutHooks } = useUser();
        logoutHooks();
      }
      return Promise.reject(new Error(res.msg || 'Error'));
    }
    return res;
  },
  error => {
    Message.error({
      content: error.msg || '系统异常',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);