import {TYPE_ALERT} from "~/types/enums";
import Page from "~/services/store/page";

export default function ({ $axios, redirect, store }) {
  $axios.onRequest(config => {
    if(!config.params.noXaccessId){
      $axios.setHeader('x-accessid', `${store.state.profile.access.id}`)

      if (store.state.profile.access.switchId) {
        $axios.setHeader('x-switch-user', `${store.state.profile.access.switchId}`)
      }

      $axios.setToken(`${store.state.profile.access.bearer}`, 'Bearer')
    }else{
      delete config.headers.common['Authorization']
      delete config.headers.common['x-accessid']
      $axios.setHeader('x-accessid', false)
      $axios.setToken(false)
    }
  })

  $axios.onResponse(response => {
  })

  $axios.onError((error) => {

    // In case of unauthorized, redirect to a specific page
    if (error.response.status === 401) {
      redirect('/login')
    }
    if (error.response.status === 403) {
      console.debug('forbidden')
    }

    if (error.response.status === 500) {
      new Page(store).addAlerts(TYPE_ALERT.ALERT, [error.response.data['hydra:description']])
    }
  })
}
