import { storage } from '@inside-library/helpers/Storage'
import { http } from '@inside-library/helpers/Http'

const state = {
  site: {},
  client: null,
  fetchedClients: {}
}

/**
 * Getters
 */
const getters = {
  getUserInformation: state => key => state[key]
}

/**
 * Actions
 */
const actions = {
  async fetchClient({ state }, payload) {
    const { lang } = payload
    try {
      const { data } = await http.get('content/clients', {
        fields: ['uuid', 'title', 'image', 'machine_name'],
        filters: {
          'machine_name:eq':
            typeof state.client === 'object'
              ? state.client.machine_name
              : state.client
        }
      })

      const client = {
        ...data[0],
        lang
      }

      state.fetchedClients[state.client] = client
      state.client = client
      storage.set('client', client)
    } catch (err) {
      throw new Error(err)
    }
  }
}

/**
 * Mutations
 */
const mutations = {
  setUserInformation(state, payload) {
    const { key, value } = payload
    const lang = storage.get('current-user').langcode

    state[key] = value

    if (key === 'client' && !(value in state.fetchedClients)) {
      this.dispatch('fetchClient', { lang })
    } else if (key === 'client') {
      const client = {
        ...state.fetchedClients[value],
        lang
      }

      state.client = client
      storage.set(key, client)
    } else {
      storage.set(key, value)
    }
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
