// SPDX-FileCopyrightText: WTF Kooperative eG <https://wtf-eg.de/>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

export default {
  namespaced: true,
  state() {
    return {
      searching: false,
      showSpinner: false,
      searched: false,
      profiles: [],
      error: false,
      errorMessage: '',
      query: {
        search: ''
      }
    }
  },
  mutations: {
    setSearching(state, searching) {
      state.searching = searching
    },
    showSpinner(state) {
      state.showSpinner = true
    },
    hideSpinner(state) {
      state.showSpinner = false
    },
    clearProfiles(state) {
      state.profiles = []
    },
    setProfiles(state, profiles) {
      state.profiles = profiles
    },
    setError(state, error) {
      state.error = error
    },
    setErrorMessage(state, errorMessage) {
      state.errorMessage = errorMessage
    },
    setQuerySearch(state, search) {
      state.query.search = search
    }
  },
  actions: {
    async search({state, commit, rootState}) {
      if (state.searching) {
        return
      }

      commit('setSearching', true)

      const timeoutId = setTimeout(() => {
        commit('showSpinner')
        commit('clearProfiles')
      }, 100)

      commit('setError', false)
      commit('setErrorMessage', '')

      const url = new URL(`${window.ki.apiUrl}/users/profiles`)
      
      if (state.query.search) {
        url.searchParams.append('search', state.query.search)
      }

      const headers = {
        Authorization: `Bearer ${rootState.token}`,
      }

      let response

      try {
        response = await fetch(url, {headers})
      } catch {
        commit('setError', true)
        commit('clearProfiles')
        commit('setSearching', false)
        commit('hideSpinner')
        return
      }

      clearTimeout(timeoutId)

      if (!response.ok) {
        commit('setError', true)
        commit('clearProfiles')
        commit('setSearching', false)
        commit('hideSpinner')
        return
      }

      const responseData = await response.json()
      commit('setProfiles', responseData.profiles)
      commit('setSearching', false)
      commit('hideSpinner')
    }
  }
}
