import type { StateCreator } from "zustand";
import type { AppState } from "../types";

export type MessagesSlice = Pick<
    AppState,
    "messages" | "addMessage" | "removeMessage" | "clearMessages"
>;

export const createMessagesSlice: StateCreator<AppState, [], [], MessagesSlice> = (set) =>
({
    messages: [],

    addMessage: (m) =>
    {
        set((s) => ({ messages: [ m, ...s.messages ].slice(0, 200) }));
    },

    removeMessage: (id) =>
    {
        set((s) => ({ messages: s.messages.filter((mm) => mm.id !== id) }));
    },

    clearMessages: () =>
    {
        set({ messages: [] });
    },
});
