import axios from "axios";
import {successRequest} from "@/core/utils/succesHandler";
import PendingNotification from "@/core/components/notifications/PendingNotification";
import {useTranslations} from "next-intl";
import useUser from "@/lib/app/hooks/useUser";
import {errorRequest, errorResponse, errorSetting} from "@/core/utils/errorHandler";
import useNetwork from "@/lib/app/hooks/useNetwork";

const defaultOptions = {
    auth: false, data: {}, requestOptions: {
        headers: {}
    }, notification: true, pending: true, success: {
        notification: {
            show: true,
        },
    }, failed: {
        notification: {
            show: true,
        },
    },
}
const useRequest = (initOptions) => {
    const network = useNetwork()
    const t = useTranslations()
    const {token, clearToken} = useUser()
    let _options = {...defaultOptions, ...initOptions}

    function requestServer(url = '', method = 'get', options) {
        _options = {..._options, ...options}
        if (_options.auth) _options = {
            ..._options, requestOptions: {
                ..._options.requestOptions,
                headers: {..._options.requestOptions.headers, authorization: `Bearer ${token}`}
            }
        }

        return new Promise((resolve, reject) => {
            if (!network.online) {
                reject()
                return
            }
            if (_options.notification && _options.failed.notification.show && _options.pending) PendingNotification(t)
            axios({
                url: url, method: method, data: _options.data, ..._options.requestOptions
            })
                .then(response => {
                    successRequest(response, t, _options)
                    resolve(response)
                })
                .catch(error => {
                    if (error.response) {
                        errorResponse(error.response, clearToken, t, _options.notification && _options.failed.notification.show)
                    } else if (error.request) {
                        errorRequest(t, _options.notification && _options.failed.notification.show)
                    } else {
                        errorSetting(t, _options.notification && _options.failed.notification.show)
                    }
                    reject(error)
                })
        });
    }

    return requestServer
}

export default useRequest