import axios from 'axios'
import { useAuthStore } from '../stores/auth'
import router from '../router'

// Use relative URL for production, or hardcoded for dev
const baseURL = import.meta.env.PROD ? '/api/v1' : 'http://localhost:8000/api/v1'

export const getBaseURL = () => baseURL


const api = axios.create({
  baseURL
})

api.interceptors.request.use((config) => {
  const authStore = useAuthStore()
  if (authStore.token) {
    config.headers.Authorization = `Bearer ${authStore.token}`
  }
  return config
})

api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response && error.response.status === 401) {
      const authStore = useAuthStore()
      authStore.logout()
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default api

