import axios_ from 'axios'
import { getActivePinia } from 'pinia'
import { useApiErrorStore } from '@/store/apiErrorStore'
import { getBackendUrl } from '@/lib/backendUrl'

const baseURL = getBackendUrl()

const axiosInstance = axios_.create({ baseURL })

axiosInstance.interceptors.response.use(
  (response) => response,
  (error) => {
    if (getActivePinia()) {
      const apiErrorStore = useApiErrorStore()
      apiErrorStore.addError(error.response)
    } else {
      console.error('Pinia not active, error not registered in store:', error.response)
    }
    return Promise.reject(error)
  }
)

export default axiosInstance
export { baseURL }
