import { BlogData } from "@/schema/blog";
import { FetchBlogParams, FetchRecentBlogParams } from "@/schema/services/blog";
import { useState } from "react";
import { fetchBlogREST, fetchRecentBlogREST } from "../rest/blog";

export function useBlogQuery() {
  const [data, setData] = useState<BlogData[]>([]);
  const [isFetching, setFetching] = useState(false);
  const [hasNext, setHasNext] = useState(false);

  async function _fetch(params: FetchBlogParams = {}) {
    setFetching(true);
    const res = await fetchBlogREST(params);
    setFetching(false);

    if (Array.isArray(res?.formattedData)) {
      if (!!params.page && params.page > 1) {
        setData((currentData) => {
          return [...currentData, ...res.formattedData];
        });
      } else {
        setData(res.formattedData);
      }
    }
    setHasNext(res?.hasNextPage ?? false);
  }

  return {
    _fetch,
    data,
    isFetching,
    hasNext,
  };
}

export function useRecentBlogQuery() {
  const [data, setData] = useState<BlogData[]>([]);
  const [isFetching, setFetching] = useState(false);

  async function _fetch(params: FetchRecentBlogParams) {
    setFetching(true);
    const res = await fetchRecentBlogREST(params);
    setFetching(false);

    if (Array.isArray(res?.formattedData)) {
      setData(res.formattedData);
    }
  }

  return {
    _fetch,
    data,
    isFetching,
  };
}
