import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken, removeToken } from '@/utils/auth'
import { DEFAULT_REQUEST_TIMEOUT } from './timeouts'

const service = axios.create({
  baseURL: '',
  timeout: DEFAULT_REQUEST_TIMEOUT
})

service.interceptors.request.use((config) => {
  const token = getToken()
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

service.interceptors.response.use(
  (response) => {
    const result = response.data

    if (result && Object.prototype.hasOwnProperty.call(result, 'code')) {
      if (result.code === 200) {
        return result
      }

      if (result.code === 401) {
        removeToken()
        ElMessage.error('登录状态已过期，请重新登录')
      } else {
        ElMessage.error(result.msg || '请求处理失败')
      }

      return Promise.reject(new Error(result.msg || '请求处理失败'))
    }

    return result
  },
  (error) => {
    if (error.response?.status === 401) {
      removeToken()
      ElMessage.error('登录状态已过期，请重新登录')
    } else {
      ElMessage.error(error.message || '网络请求失败，请稍后重试')
    }

    return Promise.reject(error)
  }
)

export default service
