import { create } from "zustand";
import { immer } from "zustand/middleware/immer";

interface CollabUsersStore {
    collabUsers: CollabUsersScheme[];

    addCollabUser: (user: CollabUsersScheme) => void;
    updateCollabUser: (userId: string, updates: Partial<CollabUsersScheme>) => void;
    setCollabUsers: (users: CollabUsersScheme[]) => void;
    removeCollabUser: (userId: string) => void;
    clearCollabUsers: () => void;
}

export const createCollabusersStore = () => {
    return create<CollabUsersStore>()(
        immer((set) => ({
            collabUsers: [],

            addCollabUser: (user) =>
                set((state) => {
                    state.collabUsers.push(user);
                }),

            updateCollabUser: (userId, updates) =>
                set((state) => {
                    const idx = state.collabUsers.findIndex((u) => u.userId === userId);
                    if (idx !== -1) {
                        Object.assign(state.collabUsers[idx], updates);
                    }
                }),

            setCollabUsers: (users) =>
                set((state) => {
                    state.collabUsers = users;
                }),

            removeCollabUser: (userId) =>
                set((state) => {
                    state.collabUsers = state.collabUsers.filter((u) => u.userId !== userId);
                }),

            clearCollabUsers: () =>
                set((state) => {
                    state.collabUsers = [];
                }),
        }))
    );
};

export type CollabUsersStoreType = ReturnType<typeof createCollabusersStore>;
