/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState } from "react";

interface IUseFecth {
  get: (params?: string) => Promise<void>;
  error: any;
  response: any;
  loading: boolean;
}

const getFullUrl = (apiHost: string, params?: string) => {
  return params ? `${apiHost}?${params}` : apiHost;
};

const useFecth = function (apiUrl: string): IUseFecth {
  const [error, setError] = useState<any>(null);
  const [response, setResponse] = useState<any | null>(null);
  const [loading, setLoading] = useState(false);

  const get = async (params?: string) => {
    setLoading(true);

    fetch(new Request(getFullUrl(apiUrl, params)))
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      return response.json();
    })
    .then((response) => {
      setResponse(response);
      setError(null);
      setLoading(false);
    }).catch((error)=>{
      setError(error);
      console.log(error)
    });

  };
  return { get, error, loading, response };
};

export default useFecth;
