import axios from 'axios'
import { useAuthStore } from '../stores/auth'

const apiBase = (import.meta.env.VITE_API_BASE || '').replace(/\/$/, '')
const request = axios.create({
  baseURL: apiBase ? `${apiBase}/api` : '/api',
  timeout: 15000
})

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

request.interceptors.response.use(
  (res) => res.data,
  (err) => {
    if (err.response?.status === 401) {
      useAuthStore().logout()
      window.location.pathname = '/admin/login'
      return Promise.reject(new Error('登录已过期，请重新登录'))
    }
    let msg = err.response?.data?.error || err.message || '请求失败'
    if (err.response?.data?.debug) {
      msg += ' (' + err.response.data.debug + ')'
    }
    return Promise.reject(new Error(msg))
  }
)

export default request
