import { apiInstance } from "@/shared/config/apiConfig";
import { IFetch } from "@/shared/types/fetch-type";
import { IList } from "@/shared/types/list-type";
import { IReport } from "@/shared/types/report-type";
import { create } from "zustand";

interface IFetchReports extends IList {
  results: IReport[];
}

interface IRatingStore extends IFetch {
  data: IFetchReports;
  getReports: (
    categories: string,
    page: number,
    sort: string
  ) => Promise<void>;
}

export const useRatingStore = create<IRatingStore>((set) => ({
  data: {
    count: 0,
    previous: null,
    next: null,
    results: [],
  },
  isLoading: false,
  error: "",
  getReports: async (
    query: string = "",
    page: number = 1,
    sort: string = ""
  ) => {
    try {
      set({ isLoading: true });

      const data = (
        await apiInstance.get<IFetchReports>(
          `/report/list_sort?sort_by=${sort}&page=${page}`
        )
      ).data;

      const searched = data.results.filter((rating) => {
        return rating.location.some((location) => {
          return location.address
            .toLowerCase()
            .includes(query.toLowerCase());
        });
      });

      data.results = [...searched];

      set({ data: data });
    } catch (error: any) {
      set({ error: error.message });
    } finally {
      set({ isLoading: false });
    }
  },
}));
