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

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

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

  return {
    url,
    config: {
      params: {
        since: onlyNonPast ? (new Date()).toISOString() : undefined,
        limit,
        offset,
      },
      headers: auth ? { Authorization: getAuthHeader() } : null,
    },
  };
};

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

const useFetchJobAds = ({
  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], jobAdFetcher, { initialData });
  return {
    data: data?.results || data,
    error,
  };
};

export default useFetchJobAds;
