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

interface State {
    history: string[];
}

interface Action {
    setHistory: (key: string) => void;
    removeKey: (key: string) => void;
    removeAllKey: () => void;
    reset: () => void;
}

const initialState: State = {
    history: [],
};
export const useSearchStore = create<State & Action>()(
    devtools(
        persist(
            (set) => {
                return {
                    ...initialState,
                    setHistory: (value: string) =>
                        set((state) => {
                            const newHistory = state.history;
                            const isPush = newHistory.indexOf(value) === -1;
                            if (isPush) {
                                newHistory.push(value);
                            }
                            return {
                                history: [...newHistory],
                            };
                        }),
                    removeKey: (key: string) => {
                        return set((state) => {
                            const history = state.history;
                            const newArray = history.filter((item) => item !== key);
                            return {
                                history: [...newArray],
                            };
                        });
                    },
                    removeAllKey: () => {
                        return set({
                            history: [],
                        });
                    },
                    reset: () => {
                        set(initialState);
                    },
                };
            },
            {
                name: "searchHistory",
                storage: createJSONStorage(() => localStorage),
            }
        ),
        { name: "searchHistory" }
    )
);
