import { login, getMe } from '@/api/auth'

const TOKEN_KEY = 'mes_token'

export default {
  namespaced: true,
  state: {
    token: localStorage.getItem(TOKEN_KEY) || '',
    user: null,
  },
  getters: {
    token: s => s.token,
    user: s => s.user,
    isLoggedIn: s => !!s.token,
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem(TOKEN_KEY, token)
    },
    SET_USER(state, user) {
      state.user = user
    },
    LOGOUT(state) {
      state.token = ''
      state.user = null
      localStorage.removeItem(TOKEN_KEY)
    },
  },
  actions: {
    async login({ commit }, { username, password }) {
      const res = await login({ username, password })
      commit('SET_TOKEN', res.data.access_token)
      commit('SET_USER', { username: res.data.username, role: res.data.role })
      return res
    },
    async fetchMe({ commit }) {
      const res = await getMe()
      commit('SET_USER', res.data)
    },
    logout({ commit }) {
      commit('LOGOUT')
    },
  }
}
