import Vuex from 'vuex'
import _ from 'lodash'
import security from '@/plugins/security'
import {
  LOG_IN_MUTATION_TYPE,
  LOG_OUT_MUTATION_TYPE,
  MEMBER_AUTHORITY_GETTER,
  IS_LOGGED_IN_GETTER_NAME,
} from '@/config/defaults'

/**
 * Auth Store
 *
 * Store mocking function to return a mock as user is logged in or logged out
 *
 * @param loggedIn
 * @param merge additional value to merge into the store
 * @returns {Store<any>}
 */
const authStore = (loggedIn, merge) => {
  let store = new Vuex.Store(
    _.merge(merge, {
      modules: {
        defaults: {
          getters: {
            getCurrentVersion: () => '',
            getAppStatus: () => () => false,
          },
          actions: {
            isMobile: () => Promise.resolve(false),
            setAppStatus: () => {},
          },
        },
        logModule: {
          getters: {
            getUnreadNotices: () => '',
          },
        },
        auth: {
          state: {
            loggedIn: loggedIn,
          },
          getters: {
            [IS_LOGGED_IN_GETTER_NAME]: state => state.loggedIn,
          },
        },
        permission: {
          state: {
            memberAuthority: {
              'my-account': ['view'],
              genealogy: ['view'],
              eshop: ['view'],
              report: ['view'],
              'bonus-statement': ['view'],
              'campaign-report': ['view'],
              'order-history': ['view'],
            },
          },
          getters: {
            [MEMBER_AUTHORITY_GETTER]: state => state.memberAuthority,
            isMemberAuthorityInitialized: () => true,
          },
        },
      },
      plugins: [
        security.registerStorePlugin(
          LOG_IN_MUTATION_TYPE,
          LOG_OUT_MUTATION_TYPE,
          IS_LOGGED_IN_GETTER_NAME,
          MEMBER_AUTHORITY_GETTER
        ),
      ],
    })
  )

  return store
}

/**
 * Logged In Store
 *
 * Returns a store mocking as though user has logged in
 *
 * @param merge additional values to merge to the store
 * @returns {Store<any>}
 */
export const loggedInStore = (merge = {}) => {
  return authStore(true, merge)
}

/**
 * Logged Out Store
 *
 * returns a store mockings as though user is logged out
 *
 * @param merge additional values to merge to the store
 * @returns {Store<any>}
 */
export const loggedOutStore = (merge = {}) => {
  return authStore(false, merge)
}

export default authStore
