import axios from 'axios'
import { useAuthStore } from '../stores/auth'
import { useMenuStore } from '../stores/menu'

export const http = axios.create({
  baseURL: import.meta.env.VITE_API_BASE || 'http://localhost:8080',
  timeout: 15000,
})

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

http.interceptors.response.use(
  (resp) => resp,
  (err) => {
    if (err?.response?.status === 401) {
      const auth = useAuthStore()
      auth.logout()
      const menu = useMenuStore()
      menu.reset()
      import('../router')
        .then(({ default: router }) => {
          const current = router.currentRoute.value
          if (current.path.startsWith('/admin') && current.path !== '/login') {
            router.replace({ path: '/login', query: { redirect: current.fullPath } })
          }
        })
        .catch(() => {})
    }
    if (err?.response?.status === 403) {
      import('../router')
        .then(({ default: router }) => {
          const current = router.currentRoute.value
          const path = current.path
          const target = path.startsWith('/admin') ? '/admin/403' : '/portal/403'
          if (path !== target) {
            router.replace({ path: target, query: { from: current.fullPath } })
          }
        })
        .catch(() => {
          if (window.location.pathname !== '/portal/403') window.location.replace('/portal/403')
        })
    }
    return Promise.reject(err)
  },
)
