import { THIRD_PARTY_APP_CHECKOUT, THIRD_PARTY_APP_PRODUCT, THIRD_PARTY_APP_PRODUCT_VIEWER } 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: 'thirdPartyApps',
  type: 'path',
  match: [THIRD_PARTY_APP_CHECKOUT, THIRD_PARTY_APP_PRODUCT, THIRD_PARTY_APP_PRODUCT_VIEWER],
  inAppArea: async function(app) {
    setTokens(app)
  },
  outAppArea: async function(app) {
    setTokens(app)
  },
}

/**
 * Set Default token in & out
 * @param app
 */
function setTokens(app) {
  let token = null
  if (
    app.$store.getters[IS_LOGGED_IN_GETTER_NAME] === true ||
    app.$store.getters[IS_LOGGED_IN_GETTER_NAME] === '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)
}
