import { THIRD_PARTY_APP_CHECKOUT } from '@/config/url-prefix'
import { SELECTED_COUNTRY } from '@/store/utils/localStorageKeys'
import { IS_LOGGED_IN_GETTER_NAME, IS_LOGGED_IN_GUEST_GETTER_NAME } from '@/config/defaults'

export default {
  name: 'thirdPartyAppsCheckout',
  type: 'path',
  match: [THIRD_PARTY_APP_CHECKOUT],
  inAppArea: async function(app, to) {
    let query = '?medium=enrolment&referrer='
    let { token, country, skip, cart, referrer } = to.query
    if (token) {
      let result = await app.$store.dispatch('guestLogin', { accessToken: token })
      if (app.$helpers.getValue(result, 'name', '').toLowerCase() === 'error') {
        referrer ? window.open(referrer, '_self') : app.$router.push('page-not-found')
      }
    } else if (
      app.$store.getters[IS_LOGGED_IN_GUEST_GETTER_NAME] === null ||
      app.$store.getters[IS_LOGGED_IN_GUEST_GETTER_NAME] === false ||
      app.$store.getters[IS_LOGGED_IN_GUEST_GETTER_NAME] === 'false'
    ) {
      if (
        app.$store.getters[IS_LOGGED_IN_GETTER_NAME] === null ||
        app.$store.getters[IS_LOGGED_IN_GETTER_NAME] === false ||
        app.$store.getters[IS_LOGGED_IN_GETTER_NAME] === 'false'
      ) {
        await app.$store.dispatch('guestLogin', query)
      }
    }

    if (localStorage.getItem(SELECTED_COUNTRY) === null) {
      await app.$store.dispatch('updateUserCountryById', false)
    }

    if (country !== undefined) {
      await app.$store.dispatch('updateSelectedCountry', country)
    }

    if (skip !== undefined) {
      await app.$store.dispatch('clearShoppingData')
      await app.$store.dispatch('3rdPartyCheckoutEnrolment/setSkipEnrolmentPrivilege', skip === 'true')
    }

    await app.$store.dispatch('eshop/setCartName', cart || 'byDzyne')
  },
}
