import { useApiSWR } from '@/hooks/useSWR';
import { SWRConfiguration } from 'swr';

export const useTableData = <T = unknown,>(
  url: string,
  options?: SWRConfiguration,
) => {
  const [baseUrl, queryString] = url.split('?');
  const q = new URLSearchParams(queryString);

  const urlString = q.toString() ? `${baseUrl}?${q.toString()}` : baseUrl;

  const { data, error, isLoading, mutate, ...others } = useApiSWR<T>(
    urlString,
    options,
  );

  return {
    refresh: () => mutate(),
    data,
    items: data?.data ?? [],
    meta: data
      ? {
          currentPage: data.current_page,
          lastPage: data.last_page,
          perPage: data.per_page,
          total: data.total,
          from: data.from,
          to: data.to,
          links: data.links ?? [],
          nextPageUrl: data.next_page_url ?? null,
          prevPageUrl: data.prev_page_url ?? null,
        }
      : undefined,
    isLoading,
    error,
    ...others,
  };
};
