import {Group, User} from "@/interfaces/user";
import {create} from "zustand";

export type Filter<T> = {id: string; filter: (x: T) => boolean};

export interface ListFilterState {
	userFilters: Filter<User>[];
	groupFilters: Filter<Group>[];
	appendUserFilter: (filter: Filter<User>) => void;
	removeUserFilter: (id: string) => void;
	clearUserFilters: () => void;
	appendGroupFilter: (filter: Filter<Group>) => void;
	removeGroupFilter: (id: string) => void;
	clearGroupFilters: () => void;
	reset: () => void;
}

export const initialState = {
	userFilters: [],
	groupFilters: [],
};

const useFilterStore = create<ListFilterState>((set) => ({
	...initialState,
	appendUserFilter: (filter: Filter<User>) => set((state) => ({userFilters: [...state.userFilters.filter((f) => f.id !== filter.id), filter]})),
	appendGroupFilter: (filter: Filter<Group>) => set((state) => ({groupFilters: [...state.groupFilters.filter((f) => f.id !== filter.id), filter]})),
	removeUserFilter: (id: string) => set((state) => ({userFilters: state.userFilters.filter((x) => x.id !== id)})),
	removeGroupFilter: (id: string) => set((state) => ({groupFilters: state.groupFilters.filter((x) => x.id !== id)})),
	clearUserFilters: () => set({userFilters: []}),
	clearGroupFilters: () => set({groupFilters: []}),
	reset: () => set(() => initialState),
}));

export default useFilterStore;
