export const state = () => ({
  user : null
})

export const getters = {
  authUser(state){
    return state.user || null
  },
  
  isAuthenticated(state){
    return !!state.user
  },
  
  isAdmin(state){
    return state.user && state.user.role && state.user.role === 'admin'
  },
}

export const actions = {
  async login({commit, state}, loginData) {
    try{
      console.log('auth.js actions login >', loginData);
      console.log('auth.js actions call $axios.$post');
      const user = await this.$axios.$post('/api/v1/users/login', loginData)
      console.log('auth.js actions call setAuthUser');
      commit('setAuthUser', user)
      return state.user
    }catch(error){
      console.log('login error')
      // console.error(error)
      return error
    }
  },
  async register(_, registerData) {
    try{
      console.log('auth.js register call await this.$axios.$post(/api/v1/users/register)')
      const user = await this.$axios.$post('/api/v1/users/register', registerData)
      console.log('auth.js register done await this.$axios.$post(/api/v1/users/register)', user)
      return user
    }catch(error){
      console.log('auth.js register error await this.$axios.$post(/api/v1/users/register)')
      // let errorMessage = 'Uuups, something went wrong, try to register again!'
      // if(error.response.data.errors) {
      //   errorMessage = error.response.data.errors.message
      // }
      return error
    }
  },
  async logout({commit}) {
    console.log('auth.js logout call await this.$axios.$post(/api/v1/users/logout)')
    try{
      const result = await this.$axios.$post('/api/v1/users/logout')
      console.log('auth.js logout done await this.$axios.$post(/api/v1/users/logout)', result)
    }catch(error){
      console.log('auth.js logout error', error)
      return error
    }

    commit('setAuthUser', null)
    return true

  },
  async getAuthUser({commit, getters, state}) {
    const authUser = getters.authUser

    if (authUser) {
      console.log('auth.js actions getAuthUser authUser ', authUser) 
      return authUser 
    }

    try {
      console.log('auth.js getAuthUser call await this.$axios.$get(/api/v1/users/me)')
      const user = await this.$axios.$get('/api/v1/users/me')
      console.log('auth.js getAuthUser done await this.$axios.$get(/api/v1/users/me) : ', user)
      commit('setAuthUser', user)
      return state.user
    }catch(error){
      console.log('auth.js getAuthUser error await this.$axios.$get(/api/v1/users/me) : ')
      commit('setAuthUser', null)
      return error
    }
  }
}


export const mutations = {
  setAuthUser(state, user) {
    state.user = user
    console.log('auth.js actions done setAuthUser');
  }
}