import { queryPorts } from "@/controller/PortController";
import { create } from "zustand";

type Ports = {
  ports: Model.PortResponse | null;
  getPorts: () => Promise<void>;
  error: string | null;
  loading?: boolean;
};

export const usePort = create<Ports>((set) => ({
  ports: null,
  getPorts: async (body?: Model.SearchThingBody) => {
    try {
      if (body === undefined) {
        body = {
          offset: 0,
          limit: 50,
          dir: "asc",
          order: "id",
        };
      }
      const response = await queryPorts(body);
      set({ ports: response.data, loading: false });
    } catch (error) {
      console.error("Error when fetch Port: ", error);
      set({ error: "Failed to fetch Port data", loading: false });
      set({ ports: null });
    }
  },
  error: null,
}));
