import { apiInstance } from "@/shared/config/apiConfig";
import { IFetch } from "@/shared/types/fetch-type";
import {
  IMyReports,
  IMyReportsList,
} from "@/shared/types/my-reports";
import { AxiosError } from "axios";
import { create } from "zustand";

interface IProfileReportsStore extends IFetch {
  data: IMyReportsList;
  getMyReports: (
    filter: string,
    page: number,
    access_token: string,
    status: number
  ) => void;
}

export const useProfileReportsStore = create<IProfileReportsStore>(
  (set) => ({
    isLoading: false,
    error: "",
    data: {
      count: 0,
      previous: null,
      next: null,
      results: [],
    },
    getMyReports: async (
      sort: string,
      page: number,
      access_token: string,
      status: number
    ) => {
      try {
        const Authorization = `Bearer ${access_token}`;
        const config = {
          headers: {
            Authorization,
          },
        };
        set({ isLoading: true });
        let data;
        if (sort === "status") {
          data = await apiInstance
            .get<IMyReportsList>(
              `/users/reports/?page=${page}&page_size=8&status=${status}`,
              config
            )
            .then((res) => res.data);
        } else {
          data = await apiInstance
            .get<IMyReportsList>(
              `/users/reports/?page=${page}&page_size=8&sort_by=${sort}`,
              config
            )
            .then((res) => res.data);
        }

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