import axios from 'axios'
import router from '../router'

const api = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000
})

api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

api.interceptors.response.use(
  (res) => res.data,
  (err) => {
    const status = err?.response?.status
    if (status === 401 || status === 403) {
      const role = localStorage.getItem('role')
      const target = role === 'ADMIN' ? '/admin/login' : '/login'
      if (router.currentRoute.value.path !== target) {
        router.push(target)
      }
    }
    const message = err?.response?.data?.message || '请求失败'
    return Promise.reject(new Error(message))
  }
)

export default api
