import useSWR, { type SWRConfiguration, type SWRResponse } from "swr";

const defaultFetcher = async (url: string): Promise<unknown> => {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Request failed: ${res.status}`);
  return res.json();
};

export function useSWRFetch<TData = unknown, TError = Error>(
  key: string | null,
  config?: SWRConfiguration<TData, TError>,
): SWRResponse<TData, TError> {
  return useSWR<TData, TError>(key, defaultFetcher as (key: string) => Promise<TData>, config);
}
