import axios from 'axios'
import { useUserStore } from '../stores/user'

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  // 开发环境使用withCredentials，生产环境关闭
  withCredentials: import.meta.env.DEV,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers['Authorization'] = `Bearer ${userStore.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    return Promise.reject(error)
  }
)

export default instance
