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

interface CommentStore {
    comments: CommentsSchema;

    // Comment operations
    addComment: (comment: CommentSchema) => void;
    setComments: (comments: CommentsSchema) => void;
    updateComment: (commentId: string, updates: Partial<CommentSchema>) => void;
    removeComment: (commentId: string) => void;

    // Reply operations
    addReply: (commentId: string, reply: Reply) => void;
    updateReply: (commentId: string, replyId: string, updates: Partial<Reply>) => void;
    removeReply: (commentId: string, replyId: string) => void;

    // Getters
    getCommentById: (commentId: string) => CommentSchema | undefined;
}

export const useCommentStore = create<CommentStore>()(
    immer((set, get) => ({
        comments: [],

        // Comment operations
        addComment: (comment) => {
            set((state) => {
                if (!state.comments.find(c => c.commentId === comment.commentId)) {
                    state.comments.push(JSON.parse(JSON.stringify(comment)));
                }
            });
        },

        setComments: (comments) => {
            set((state) => {
                state.comments = comments;
            });
        },

        updateComment: (commentId, updates) => {
            set((state) => {
                const comment = state.comments.find(c => c.commentId === commentId);
                if (comment) {
                    Object.assign(comment, updates);
                }
            });
        },

        removeComment: (commentId) => {
            set((state) => {
                state.comments = state.comments.filter(c => c.commentId !== commentId);
            });
        },

        // Reply operations
        addReply: (commentId, reply) => {
            set((state) => {
                const comment = state.comments.find(c => c.commentId === commentId);
                if (comment) {
                    comment.replies.push(reply);
                }
            });
        },

        updateReply: (commentId, replyId, updates) => {
            set((state) => {
                const comment = state.comments.find(c => c.commentId === commentId);
                if (comment) {
                    const reply = comment.replies.find(r => r.replyId === replyId);
                    if (reply) {
                        Object.assign(reply, updates);
                    }
                }
            });
        },

        removeReply: (commentId, replyId) => {
            set((state) => {
                const comment = state.comments.find(c => c.commentId === commentId);
                if (comment) {
                    comment.replies = comment.replies.filter(r => r.replyId !== replyId);
                }
            });
        },

        // Getter
        getCommentById: (commentId) => {
            return get().comments.find(c => c.commentId === commentId);
        },
    }))
);
