import { RESUME_PAYMENT_APP } from '@/config/url-prefix'
import { API_GUEST_TOKEN, API_TOKEN_KEY, API_TOKEN } from '@/store/utils/localStorageKeys'
import { IS_LOGGED_IN_GETTER_NAME } from '@/config/defaults'
import { setDefaultToken } from '@/store/utils/api'

export default {
  name: 'thirdPartyAppsResumePayment',
  type: 'path',
  match: RESUME_PAYMENT_APP,
  inAppArea: async function(app) {
    await setTokens(app)
  },
  outAppArea: function(app) {
    setTokens(app)
  },
}

/**
 * Set Default token in & out
 * @param app
 */
async function setTokens(app) {
  let query = '?medium=enrolment&referrer='
  await app.$store.dispatch('guestLogin', query)
  let token = null
  if (app.$store.getters[IS_LOGGED_IN_GETTER_NAME].toString() === 'true') {
    token = localStorage.getItem(API_TOKEN)
    localStorage.setItem(API_TOKEN_KEY, API_TOKEN)
  } else {
    token = localStorage.getItem(API_GUEST_TOKEN)
    localStorage.setItem(API_TOKEN_KEY, API_GUEST_TOKEN)
  }
  setDefaultToken(token)
}
