import router from '@/router';
import { useUserStore } from '@/stores';
import { createHttpClient, getAppEnvConfig } from '@/utils';
import type { AxiosError } from 'axios';

export const userClient = createHttpClient({
  requestInterceptor: (config) => {
    const userStore = useUserStore();
    const { lampAuthorization, lampClientId, lampClientSecret } = getAppEnvConfig();
    const newAuthorization = window.btoa(`${lampClientId}:${lampClientSecret}`);
    const authorization = lampAuthorization.trim() !== '' ? lampAuthorization : newAuthorization;
    config.headers.set('accept-language', 'zh-CN,zh;q=0.9');
    config.headers.set('accept', 'application/json, text/plain, */*');
    config.headers.set('Applicationid', '');
    config.headers.set('Tenantid', '1');
    config.headers.set('Authorization', authorization);
    config.headers.set('token', userStore.userLoginResult?.token ?? '');
    return config;
  },
  responseInterceptor: (response) => {
    return response;
  },
  responseErrorInterceptor: (error) => {
    const err = error as AxiosError;
    if (err.response?.status === 401) {
      window.$message.error('登录超时，请重新登录');
      const userStore = useUserStore();
      userStore.resetStore();
      router.push({ path: '/login' });
    }
    return Promise.reject(error);
  },
});
