import type { RouteLocationRaw } from 'vue-router'
import axios from 'axios'
import router from '@/router'
import { useAuthStore } from '@/stores'

export const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  withCredentials: true,
  headers: {
    Accept: 'application/json',
  },
})

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

  config.headers['X-Forkiva-Locale'] = localStorage.getItem('current_locale') || 'en'
  return config
})

api.interceptors.response.use(
  response => response,
  async error => {
    if (error.response?.status === 401 && (!error?.config?.url?.includes('/auth/login'))) {
      const auth = useAuthStore()
      auth.logout()
      await router.push({ name: 'login' } as unknown as RouteLocationRaw)
    } else {
      throw error
    }
  },
)
