import { create } from "zustand";
import { type CategoryType, type CategoryTreeNode } from "../types/Types";

export type CategoryStoreType = {
  selectedCategory: CategoryType | null;
  categories: CategoryTreeNode[];
  setSelectedCategory: (category: CategoryType | null) => void;
  setCategories: (categories: CategoryTreeNode[]) => void;
  addCategory: (category: CategoryTreeNode) => void;
  updateCategory: (id: string, category: Partial<CategoryTreeNode>) => void;
  removeCategory: (id: string) => void;
};

export const useCategoryStore = create<CategoryStoreType>((set) => ({
  selectedCategory: null,
  categories: [],
  setSelectedCategory(category) {
    set({ selectedCategory: category });
  },
  setCategories(categories) {
    set({ categories });
  },
  addCategory(category) {
    set((state) => ({
      categories: [...state.categories, category],
    }));
  },
  updateCategory(id, category) {
    set((state) => ({
      categories: state.categories.map((cat) =>
        cat._id === id ? { ...cat, ...category } : cat
      ),
    }));
  },
  removeCategory(id) {
    set((state) => ({
      categories: state.categories.filter((cat) => cat._id !== id),
    }));
  },
}));
