// user store
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";

import { IUserProfile } from "../types/user";

export type StoreType = {
  user: IUserProfile | null;
  loading: boolean;
  userConnected: boolean;
  setUser: (userData: IUserProfile | null) => void;
  setLoading: (newLoading: boolean) => void;
  setUserConnected: (connectedStatus: boolean) => void;
};

export const useUserStore = create<StoreType>()(
  persist(
    (set, get) => ({
      user: get()?.user ?? null, // Initial state for user info
      loading: true, // Tracks if user data is loading
      userConnected: get()?.userConnected ?? false, // initial user auth status
      setUser: (newUser: any) => set({ user: newUser, userConnected: true }), // Action to update user info
      setLoading: (newLoading: any) => set({ loading: newLoading }), // Action to update loading state
      setUserConnected: (connectedStatus: boolean) =>
        set({ userConnected: connectedStatus }), // Action to update the user auth status
    }),
    {
      name: "userStore",
      storage: createJSONStorage(() => sessionStorage),
    },
  ),
);
