import { inject } from 'vue';
import { AxiosInstance, AxiosRequestConfig } from 'axios';
import { useUiKitConfigStore } from '@/configs/store/use-ui-kit-config.store';
import { storeToRefs } from 'pinia';

export default function (authToken: string = '') {
    const axiosUiKitConfig = inject<AxiosInstance>('axiosUiKitConfig');

    const uiKitConfigStore = useUiKitConfigStore();
    const { userAuthToken } = storeToRefs(uiKitConfigStore);

    userAuthToken.value = authToken;

    axiosUiKitConfig?.interceptors.request.use((config) => {
        if (userAuthToken.value) config.headers.Authorization = `Bearer ${userAuthToken.value}`;
        return config;
    });

    const get = async <TResult, TParams = any>(
        endpoints: string,
        params?: TParams,
    ): Promise<TResult> => {
        return axiosUiKitConfig?.get(endpoints, { params }).then(({ data }) => data);
    };

    const post = async <TResult, TData = any>(
        endpoints: string,
        formData?: TData,
        config?: AxiosRequestConfig,
    ): Promise<TResult> => {
        return axiosUiKitConfig?.post(endpoints, formData, config).then(({ data }) => data);
    };

    const patch = async <TResult, TData = any>(
        endpoints: string,
        formData?: TData,
    ): Promise<TResult> => {
        return axiosUiKitConfig?.patch(endpoints, formData).then(({ data }) => data);
    };

    const put = async <TResult, TData = any>(
        endpoints: string,
        formData?: TData,
    ): Promise<TResult> => {
        return axiosUiKitConfig?.put(endpoints, formData).then(({ data }) => data);
    };

    const remove = async <TResult, TData = any>(
        endpoints: string,
        params?: TData,
    ): Promise<TResult> => {
        return axiosUiKitConfig?.delete(endpoints, { params }).then(({ data }) => data);
    };

    return {
        get,
        post,
        patch,
        remove,
        put,
    };
}
