import routes from './routes.js'
import token from './token.js'

export default ($env) => {
  token.wrapAxios($env.$axios)
  $env.$G.token = token
  let user = token.body()
  $env.$G.user = user


  $env.$router.addRoutes(routes)
  $env.$router.beforeEnter = async (to, from, next) => {
    if (to.meta && to.meta.auth) {
      if (token.isExpired()) {
        await token.refresh()
      }
      if (token.isExpired()) {
        token.logout(to.fullPath)
        return false
      }
      if (!token.check('app', '', 2)) {
        next('/')
      }
    } else {
      next();
    }
  };
  $env.$axios.interceptors.response.use(function(response) {
    return response?.data || response;
  }, function(error) {
    error = error?.response?.data || error?.response || error
    return Promise.reject(error);
  });
  $env.$axios.get('/api/cfg').then(res => {
    $env.$G.cfg = res
    console.log(res)
  })
}
