import { querySearchThings } from "@/controller/DeviceController";
import { create } from "zustand";

type ThingState = {
  things: Model.Thing[] | null;
  getThings: (body: Model.SearchThingBody) => Promise<void>;
  error: string | null;
  loading?: boolean;
};

export const useThings = create<ThingState>((set) => ({
  things: null,
  getThings: async (body: Model.SearchThingBody) => {
    set({ loading: true, error: null });
    try {
      const response = await querySearchThings(body);
      console.log("Things fetching API: ", response.data.things?.length);

      set({ things: response.data.things ?? [], loading: false });
    } catch (error) {
      console.error("Error when fetch things: ", error);
      set({
        error: "Failed to fetch things data",
        loading: false,
        things: null,
      });
    }
  },
  error: null,
  loading: false,
}));
