import Vue from 'vue'
import { getToken, setToken, getUser, setUser, clearAuth } from '@/utils/auth'
import { request } from '@/utils/request'

export const store = Vue.observable({
  token: getToken(),
  user: getUser()
})

export function isLoggedIn() {
  return !!store.token
}

export function isAdmin() {
  return !!(store.user && store.user.is_admin)
}

export function setAuth(token, user) {
  store.token = token || ''
  store.user = user || null
  setToken(token)
  setUser(user)
}

export function logout() {
  store.token = ''
  store.user = null
  clearAuth()
}

export async function refreshUser() {
  try {
    const user = await request({ url: '/auth/me' })
    store.user = user
    setUser(user)
    return user
  } catch (err) {
    return null
  }
}
