import { baseAPI } from "@/shared/api/baseAPI";
import { IFetch } from "@/shared/types/fetch-type";
import { IList } from "@/shared/types/list-type";
import { IReport } from "@/shared/types/report-type";
import axios from "axios";
import { create } from "zustand";

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

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

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

      const data = (
        await axios.get<IFetchReports>(`${baseAPI}/report/`)
      ).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 });
    }
  },
}));
