import axios from 'axios'
import { ElMessage } from 'element-plus'

const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
})

// Request interceptor: attach JWT token + AbortController support
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// Response interceptor: handle 401 gracefully
let isRedirecting = false
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      // Prevent redirect loops: only redirect if not already on login page
      if (!window.location.pathname.startsWith('/login') && !isRedirecting) {
        isRedirecting = true
        ElMessage.warning('登录已过期，请重新登录')
        // Use a small delay to allow the current UI to settle
        setTimeout(() => {
          window.location.href = '/login'
          isRedirecting = false
        }, 500)
      }
    } else if (error.response?.status === 403) {
      ElMessage.error('没有权限执行此操作')
    } else if (error.response?.status >= 500) {
      ElMessage.error('服务器错误，请稍后重试')
    }
    return Promise.reject(error)
  }
)

export default api
