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

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

// Request interceptor — attach JWT token
client.interceptors.request.use(config => {
  const token = localStorage.getItem('accessToken')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// Response interceptor — normalize errors
client.interceptors.response.use(
  response => {
    const { data } = response
    // ApiResult wrapper
    if (data && data.code !== undefined) {
      if (data.code === 200) return data
      if (data.code === 401) {
        localStorage.removeItem('accessToken')
        window.location.hash = '#/login'
        return Promise.reject(new Error('登录已过期'))
      }
      return Promise.reject({ ...data, _handled: true })
    }
    return data
  },
  error => {
    const { response } = error
    if (response && response.status === 409) {
      return Promise.reject({
        code: 409,
        message: '数据已被他人修改，请刷新后重试',
        conflictVersion: response.data?.conflictVersion,
        _handled: true
      })
    }
    if (!error._handled) {
      ElMessage.error(error.message || '请求失败')
    }
    return Promise.reject(error)
  }
)

export default client
