import type { InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { ResultEnum } from '@/enums/HttpEnum'
import { useAuthStore, useUserStore } from '@/stores'
import router from '@/router'
import { LOGIN_URL } from '@/constants'
const defaultRequestInterceptors = (config: InternalAxiosRequestConfig) => {
  const userStore = useUserStore()
  if (config.headers && typeof config.headers.set === 'function') {
    config.headers.set('Authorization', 'Bearer ' + userStore.token)
    config.headers.set('clientId', import.meta.env.VITE_APP_CLIENT_ID)
  }
  return config
}

const defaultResponseInterceptors = (response: AxiosResponse) => {
  const { code, msg } = response.data
  const userStore = useUserStore()
  const authStore = useAuthStore()

  if (response?.config?.responseType === 'blob') {
    // 如果是文件流，直接过
    return response
  } else if (code === ResultEnum.SUCCESS) {
    return response.data
  } else if (code === ResultEnum.FORBIDDEN) {
    ElMessage.error('无权限')
    return response.data
  } else if (code === ResultEnum.OVERDUE) {
    userStore.clear()
    authStore.clear()
    if (router.currentRoute.value.path !== LOGIN_URL) {
      router.replace(LOGIN_URL)
    }
    ElMessage.warning('认证失效，请重新登录！')
  } else {
    console.error(msg)
    ElMessage.error(msg)
  }
}
export { defaultResponseInterceptors, defaultRequestInterceptors }
