import { loginAPI } from '@/api/user'
import { removeTokenCookies, setTokenCookies } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: '',
    userInfo: {}
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setTokenCookies(newToken)
    },

    setUserInfo(state, newUserInfo) {
      state.userInfo = newUserInfo
    },

    clearTokenAndUserInfo(state) {
      state.token = ''
      state.userInfo = {}
      removeTokenCookies()
    }
  },
  actions: {
    async asyncSetToken(text, data) {
      const res = await loginAPI(data)
      text.commit('setToken', res.data.token)
      text.commit('setUserInfo', res.data.user)
    }
  }
}
