import { apiInstance } from "@/shared/config/apiConfig";
import { IFetch } from "@/shared/types/fetch-type";
import { INewsList } from "@/shared/types/news-type";
import { AxiosError } from "axios";
import { create } from "zustand";

interface useNewsStore extends IFetch {
  data: INewsList;
  getNews: (page: number) => void;
}

export const useNewsStore = create<useNewsStore>((set) => ({
  data: {
    count: 0,
    previous: null,
    next: null,
    results: [],
  },
  error: "",
  isLoading: false,
  getNews: async (page: number) => {
    try {
      set({ isLoading: true });

      const res = await apiInstance.get(`/news/?page${page}`);

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