import {
  queryChilrentOfGroups,
  queryUserGroup,
} from "@/controller/GroupController";
import { create } from "zustand";

type Groups = {
  groups: Model.GroupResponse | null;
  childrenOfGroups?: Model.GroupResponse | null;
  getChildrenOfGroups: (group_id: string) => Promise<void>;
  getUserGroups: () => Promise<void>;
  error: string | null;
  loading?: boolean;
};

export const useGroup = create<Groups>((set) => ({
  groups: null,
  childrenOfGroups: null,
  getUserGroups: async () => {
    try {
      const response = await queryUserGroup();
      set({ groups: response.data, loading: false });
    } catch (error) {
      console.error("Error when fetch Port: ", error);
      set({ error: "Failed to fetch Port data", loading: false });
      set({ groups: null });
    }
  },
  getChildrenOfGroups: async (group_id: string) => {
    try {
      set({ loading: true });
      const response = await queryChilrentOfGroups(group_id);
      set({ childrenOfGroups: response.data, loading: false });
    } catch (error) {
      console.error("Error when fetching children of groups: ", error);
      set({ error: "Failed to fetch children of groups", loading: false });
      set({ childrenOfGroups: null });
    }
  },
  error: null,
}));
