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

export const ndmClient = createHttpClient({
  requestInterceptor: async (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);
    const staticCode = config.url?.split('/api').at(0)?.split('/').at(-1) ?? '';
    config.headers.set('token', userStore.lampLoginResultRecord?.[staticCode]?.token ?? '');
    return config;
  },
  responseErrorInterceptor: async (error) => {
    const err = error as AxiosError;
    if (err.response?.status === 401) {
      // 当车站请求由于token时效而失败时，需要重新登录车站获取token，然后重新请求
      const stationCode = err.config?.url?.split('/api').at(0)?.split('/').at(-1) ?? '';
      const userStore = useUserStore();
      await userStore.lampLogin(stationCode);
      error.config.headers.token = userStore.lampLoginResultRecord?.[stationCode]?.token ?? '';
      return ndmClient.clientInstance(error.config);
    }
    return Promise.reject(error);
  },
});
