import { useQuery } from '@tanstack/react-query';
import { BASE_URI } from '@/helpers/constants';
import myAxios from '@/helpers/myAxios';
import authRequest from '@/helpers/authRequest';

interface SearchParams {
    [key: string]: string | number | boolean | undefined | null;
}

const generateUrl = (endpoint: string, searchParams: SearchParams = {}): string => {
    let url = `${endpoint}`;

    Object.keys(searchParams).forEach(key => {
        if (searchParams[key] === undefined || searchParams[key] === null) {
            delete searchParams[key];
        }
    });

    const paramKeys = Object.keys(searchParams);

    if (!paramKeys?.length) {
        return url;
    }

    paramKeys.forEach((key, index) => {
        url += `${index === 0 ? '?' : '&'}${key}=${searchParams[key]}`;
    });

    return url;
};

interface UseMainFetchParams {
    key: string | string[];
    endpoint: string;
    options?: any;
    method?: 'get' | 'post' | 'put' | 'delete';
    searchParams?: SearchParams;
    generateData?: (val: any) => any;
}

const useMainFetch = ({
    key,
    endpoint,
    options,
    method = 'get',
    searchParams = {},
    generateData = (val: any) => val,
}: UseMainFetchParams) => {
    const transformedParams = generateUrl(endpoint, searchParams);

    // return useQuery([key, { ...searchParams }], () => myAxios[method](transformedParams).then(data => generateData(data)), { ...options });
    return useQuery([key, { ...searchParams }], () => authRequest[method](transformedParams).then(data => generateData(data)), { ...options });
};

export default useMainFetch;
