import { baseAPI } from "@/Shared/API/baseAPI";
import { IFetch } from "@/Shared/types";
import axios from "axios";
import { create } from "zustand";
import { IReport } from "./types";

interface IRatingStore extends IFetch {
  data: IReport;
  getRatings: (query: string) => Promise<void>;
}

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

      const data = (await axios.get<IReport>(`${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({ loading: false });
    }
  },
}));
