import type { UserProfileData } from "@/api/types";
import { client, safeClient } from "@/api";

interface State {
  userProfile: UserProfileData | null;
}

export const useUserStore = defineStore("user", () => {
  const token = useStorage<string | null>("user-token", null);
  const state = reactive<State>({
    userProfile: null,
  });

  const isAuthenticated = computed(() => !!token.value);

  async function updateProfile() {
    const { data } = await safeClient(client.api.user.profile.get(), { silent: true });
    state.userProfile = data.value || null;
  }

  function setToken(value: string) {
    localStorage.setItem("user-token", value);
    token.value = value;
  }

  function signOut() {
    token.value = null;
    state.userProfile = null;
  }

  return {
    ...toRefs(state),
    token,
    isAuthenticated,
    signOut,
    setToken,
    updateProfile,
  };
});
