import axios from "axios";

const authViewer = (error) => {
  console.log(error);
  // if (error.response.status === 500) {
  //   const {pathname} = new URL(window.location.href)
  //   sessionStorage.setItem("pathname", pathname)
  //   localStorage.removeItem('token')
  //   window.location.replace('/auth')
  // }
}

const post = async (path, data, onError) => {
  const token = localStorage.getItem('token')
  console.log(token);
  if(!token) {
    window.location.replace('/auth')
  }
  return axios.post(`${import.meta.env.VITE_API_ADDR}${path}`, data, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  })
    .then(r => r.data)
    .catch(error => {
      onError && onError(error)
      console.error('Error post request:', error)
      authViewer(error)
    })
}

const get = async (path, success_callback) => {
  return await axios.get(`${import.meta.env.VITE_API_ADDR}${path}`)
    .then(success_callback)
    .catch(error => {
      console.error('Error post request:', error)
      authViewer(error)
    })
}


export {get, post}
