import { ref, type Ref } from "vue";
import { defineStore } from "pinia";
import type { CurrentUser } from "@/types/user.types";
import userService from "@/services/user.service";

const tokenKey = "token";

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem(tokenKey));
  const currentUser: Ref<CurrentUser | null> = ref(null);

  function setToken(_token: string) {
    token.value = _token;
    localStorage.setItem(tokenKey, _token);
  }

  function setCurrentUser(user: CurrentUser) {
    currentUser.value = user;
  }

  function isLoginIn() {
    return token.value && token.value.trim() != "";
  }

  function checkLogin() {
    return userService.checkLogin();
  }

  function logout() {
    setToken("");
  }

  return {
    token,
    currentUser,
    setToken,
    setCurrentUser,
    isLoginIn,
    logout,
    checkLogin,
  }
});
