import { Message, Modal } from '@arco-design/web-vue';
import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import axios from 'axios';
import i18n from '@/locale';
import { useUserStore } from '@/store';
import { getToken } from '@/utils/auth';

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

let initialized = false;

function t(key: string) {
  return i18n.global.t(key);
}

export function setupHttp() {
  if (initialized) {
    return;
  }
  initialized = true;

  const baseURL = import.meta.env.VITE_API_BASE_URL?.trim();
  if (baseURL) {
    axios.defaults.baseURL = baseURL;
  }

  axios.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      const token = getToken();
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    },
    (error) => Promise.reject(error),
  );

  axios.interceptors.response.use(
    (response: AxiosResponse<HttpResponse>) => {
      const res = response.data;
      if (res.code !== 20000) {
        Message.error({
          content: res.msg || t('http.error.default'),
          duration: 5 * 1000,
        });
        if (
          [50008, 50012, 50014].includes(res.code) &&
          response.config.url !== '/api/user/info'
        ) {
          Modal.error({
            title: t('http.logout.title'),
            content: t('http.logout.content'),
            okText: t('http.logout.okText'),
            async onOk() {
              const userStore = useUserStore();
              await userStore.logout();
              window.location.reload();
            },
          });
        }
        return Promise.reject(new Error(res.msg || t('http.error.default')));
      }
      return res as unknown as AxiosResponse<HttpResponse>;
    },
    (error) => {
      Message.error({
        content: error.msg || t('http.error.request'),
        duration: 5 * 1000,
      });
      return Promise.reject(error);
    },
  );
}
