import axios from 'axios'

const AxiosType = {
  INTERNAL: 'Internal',
  EXTERNAL: 'External',
}

export function useAxios() {
  const getInstances = (url) => {
    let type = AxiosType.INTERNAL
    url.startsWith('http') ? (type = AxiosType.EXTERNAL) : ''

    return axios.create({
      baseURL: type === AxiosType.INTERNAL ? process.env.NEXT_PUBLIC_API_SERVER_PATH : '',
      headers: {
        Accept: 'application/json',
      },
    })
  }

  axios.interceptors.request.use((config) => {
    // config['Authorization'] = localStorage.getItem('token')
    //TODO: 인터셉터에서 추가 로직 구현
    return config
  })

  axios.interceptors.request.use(undefined, (error) => {
    //TODO: 인터셉터에서 에러 처리 로직 구현
    // if (error.isAxiosError && e.response?.status === 401) {
    //   localStorage.removeItem('token')
    // }
  })

  const get = async ({ url }) => {
    return await getInstances(url)
      .get(url)
      .then((res) => res.data)
      .catch(console.error)
  }

  const post = async ({ url, data }) => {
    return await getInstances(url)
      .post(url, data)
      .then((res) => res.data)
      .catch(console.error)
  }

  const put = async ({ url, data }) => {
    return await getInstances(url)
      .put(url, data)
      .then((res) => res.data)
      .catch(console.error)
  }

  const patch = async ({ url, data }) => {
    return await getInstances(url)
      .patch(url, data)
      .then((res) => res.data)
      .catch(console.error)
  }

  const del = async ({ url }) => {
    return await getInstances(url)
      .delete(url)
      .then((res) => res.data)
      .catch(console.error)
  }

  return { get, post, put, patch, del }
}
