import { apiInstance } from "@/shared/config/apiConfig";
import { IFetch } from "@/shared/types/fetch-type";
import { IList } from "@/shared/types/list-type";
import { IStatistics } from "@/shared/types/statistics-type";
import { AxiosError } from "axios";
import { create } from "zustand";

interface IStatisticsStore extends IFetch {
  data: IStatistics[];
  getStatistics: (
    endpoint: string,
    sort: string,
    query: string
  ) => void;
}

export const useStatisticsStore = create<IStatisticsStore>((set) => ({
  isLoading: false,
  error: "",
  data: [],
  getStatistics: async (
    endpoint: string,
    sort: string,
    query: string = ""
  ) => {
    try {
      set({ isLoading: true });
      const response = await apiInstance.get<IStatistics[]>(
        `/report/${endpoint}/stats?sort_by=${sort}`
      );

      let data = response.data.filter((loc) =>
        loc.name.toLowerCase().includes(query.toLowerCase())
      );

      set({ data: data });
    } catch (error: unknown) {
      if (error instanceof AxiosError) {
        set({ error: error.message });
      } else {
        set({ error: "an error ocured" });
      }
    } finally {
      set({ isLoading: false });
    }
  },
}));
