// src/utils/request.ts
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

// 创建 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // 从环境变量读取
  timeout: 10000,
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 可添加 token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => response.data,
  (error) => {
    // 统一错误处理
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

export default service