import { defineStore } from 'pinia'

export const useAuthStore = defineStore('user', () => {
  const isLogin = ref(false)
  const user = ref<any>(null)

  function checkAuth() {
    const token = localStorage.getItem('token')
    const userStr = localStorage.getItem('user')

    if (token && userStr) {
      try {
        user.value = JSON.parse(userStr)
        isLogin.value = true
      }
      catch {
        isLogin.value = false
        user.value = null
      }
    }
    else {
      isLogin.value = false
      user.value = null
    }

    return isLogin.value
  }

  function logout() {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    isLogin.value = false
    user.value = null
  }

  return {
    isLogin,
    user,
    checkAuth,
    logout,
  }
})
