import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import type { FullUser, PartialUser, UserId } from "~/lib/api/types";

type UsersStore = {
    users: Record<UserId, PartialUser>;
    currentUserId: UserId | undefined;
    addUser: (user: PartialUser) => void;
    removeUser: (userId: UserId) => void;
    setCurrentUserId: (userId: UserId) => void;
    getCurrentUser: () => FullUser | undefined;
};

export const useUsersStore = create<UsersStore>()(
    immer((set, get) => ({
        users: {},
        currentUserId: undefined,
        addUser: (user) =>
            set((state) => {
                if (user.id !== get().currentUserId) state.users[user.id] = user;
                else {
                    const currentUser = get().users[user.id];
                    if (currentUser) state.users[user.id] = { ...currentUser, ...user };
                    else state.users[user.id] = user;
                }
            }),
        removeUser: (userId) =>
            set((state) => {
                delete state.users[userId];
            }),

        setCurrentUserId: (userId) =>
            set((state) => {
                state.currentUserId = userId;
            }),

        getCurrentUser: () => {
            const currentUserId = get().currentUserId;
            return currentUserId ? (get().users[currentUserId] as FullUser) : undefined;
        },
    })),
);
