import axios from 'axios'
import router from '@/router'

const apiClient = axios.create({ headers: { 'Content-Type': 'application/json' } })

let isHandlingAuthError = false
async function handleAuthError(status) {
  if (isHandlingAuthError) {
    return
  }
  isHandlingAuthError = true
  try {
    try {
      await apiClient.post('/public-api/logoutProcess')
    } catch (e) {
      // 로그아웃 안되도 무시
    }
    if (router.currentRoute.value.path != '/login') {
      router.replace({
        path: '/login',
        query: {
          reason: String(status),
        },
      })
    }
  } finally {
    setTimeout(() => {
      isHandlingAuthError = false
    }, 20)
  }
}

apiClient.interceptors.response.use(
  (response) => response,
  async (error) => {
    const status = error?.response?.status
    // 기타 오류 처리시 로직 추가
    if (status === 401 || status === 403) {
      await handleAuthError(status)
    }
    return Promise.reject(error)
  },
)

export function useApiClient() {
  return apiClient
}

export default apiClient
