import { useRef } from "react";
import useSWR from "swr";
import isDeepEqual from "fast-deep-equal/react";
import axios, { AxiosRequestConfig } from "axios";
import Post from "@models/Feed";
import { getAuthHeader } from "@utils/auth";
import { URL, Options } from "@api/feedApi";

const feedFetcher = (url: string, config?: AxiosRequestConfig) => axios.get(url, config).then((res) => res.data);

const generateFetchParams = (id = "", options: Options = {}) => {
  const url = `${URL}${id}`;
  const { auth, limit, offset } = options;

  return {
    url,
    config: {
      params: {
        limit,
        offset,
      },
      headers: auth ? { Authorization: getAuthHeader() } : null,
    },
  };
};

interface FetchArguments {
  initialData?: Post | Post[],
  id?: string;
  options?: Options
}

const useFetchFeed = ({
  initialData,
  id = "",
  options = {},
}: FetchArguments) => {
  const { url, config } = generateFetchParams(id, options);

  // Use ref, since config dependency is non-primitive => without this we have infinite fetch loop
  const configRef = useRef(config);
  if (!isDeepEqual(configRef.current, config)) {
    configRef.current = config;
  }

  const { data, error } = useSWR([url, configRef.current], feedFetcher, { initialData });
  return {
    data: data?.results || data,
    error,
  };
};

export default useFetchFeed;
