import { NoticeRep, updateGlobalNoticeApi } from "@/api/home";
import { Result } from "@/types";
import { create } from "zustand";

interface State {
    sourceMap: Map<number, NoticeRep>;
    unread: number; // 未读数量
    notices: NoticeRep[]; // 总数据
}

interface Action {
    setSourceMap: (key: number, value: NoticeRep) => void;
    hasValue: (key: number) => boolean;
    setNotices: (notices: NoticeRep[], unread: number) => void;
    setReadNotices: (id: number) => Promise<Result<any>>;
}

const initialState: State = {
    sourceMap: new Map(),
    unread: 0,
    notices: [],
};

export const useGlobalNoticeStore = create<State & Action>()((set, get) => {
    return {
        ...initialState,
        setSourceMap: (key, value) =>
            set((state) => {
                const newMap = new Map(state.sourceMap);
                newMap.set(key, value);
                return { sourceMap: newMap };
            }),

        hasValue: (key) => get().sourceMap.has(key),
        setNotices: (notices, unread: number) => set((state) => ({ ...state, notices, unread })),
        setReadNotices: (id: number) => {
            return updateGlobalNoticeApi(id);
        },
        reset: () => set(initialState),
    };
});
