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

const request = axios.create({
  baseURL: '/api/v1',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
})

// Request interceptor — inject Authorization token
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// Response interceptor — handle business codes and auth errors
request.interceptors.response.use(
  (response) => {
    const res = response.data

    // Success: code === 0
    if (res.code === 0) {
      return res
    }

    // Auth error: 40100–40199 → clear token and redirect to login
    if (res.code >= 40100 && res.code <= 40199) {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      ElMessage.error('登录已过期，请重新登录')
      // Avoid circular import by using window.location
      window.location.href = '/login'
      return Promise.reject(new Error(res.message || '未授权'))
    }

    // Other business error
    ElMessage.error(res.message || '请求失败')
    return Promise.reject(new Error(res.message || '请求失败'))
  },
  (error) => {
    // Network / HTTP errors
    if (error.response) {
      const status = error.response.status
      if (status === 401) {
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        ElMessage.error('登录已过期，请重新登录')
        window.location.href = '/login'
        return Promise.reject(error)
      }
      if (status === 403) {
        ElMessage.error('无权限访问')
        return Promise.reject(error)
      }
      if (status === 404) {
        ElMessage.error('请求的资源不存在')
        return Promise.reject(error)
      }
      if (status >= 500) {
        ElMessage.error('服务器内部错误，请稍后重试')
        return Promise.reject(error)
      }
    }
    if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
      ElMessage.error('请求超时，请检查网络连接')
      return Promise.reject(error)
    }
    ElMessage.error(error.message || '网络错误')
    return Promise.reject(error)
  }
)

export default request
