import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { isJwtExpired } from '@/utils/jwt'
import { useAuthStore } from '@/stores/auth'

const client = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL ?? '/api',
  timeout: 15000,
})

if (import.meta.env.DEV) {
  client.interceptors.request.use((config) => {
    console.debug('[tenant-platform][HTTP] request', {
      method: config.method?.toUpperCase(),
      url: config.baseURL ? `${config.baseURL}${config.url ?? ''}` : config.url,
      params: config.params,
    })
    return config
  })
  client.interceptors.response.use((res) => {
    console.debug('[tenant-platform][HTTP] response', {
      status: res.status,
      url: res.config.url,
    })
    return res
  })
}

client.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token && !isJwtExpired(token)) {
    config.headers.Authorization = `Bearer ${token}`
  } else if (token && isJwtExpired(token)) {
    useAuthStore().logout()
    if (router.currentRoute.value.path !== '/login') {
      router.push('/login?reason=' + encodeURIComponent('登录已失效，请重新登录'))
    }
    return Promise.reject(new Error('登录已失效，请重新登录'))
  }
  return config
})

function handleAuthFailure(message: string) {
  useAuthStore().logout()
  if (router.currentRoute.value.path !== '/login') {
    router.push('/login')
  }
  ElMessage.error(message)
}

client.interceptors.response.use(
  (res) => res,
  (error) => {
    const status = error.response?.status
    if (status === 401) {
      handleAuthFailure('登录已失效，请重新登录')
      return Promise.reject(error)
    }
    if (status === 403) {
      const msg = error.response?.data?.message ?? '当前账号无权限访问该资源'
      ElMessage.error(msg)
      return Promise.reject(error)
    }
    const msg = error.response?.data?.message ?? '请求失败'
    ElMessage.error(msg)
    return Promise.reject(error)
  },
)

export default client
