import { errorResponse } from "@/core/utils/errorResponse";
import { GET_CSRF } from "@/core/utils/routes";
import { successRequest } from "@/core/utils/successRequest";
import axios from "axios";

const getCsrfToken = async () => {
    try {
        const response = await axios.get(GET_CSRF);
        return response.data.data;
    } catch (error) {
        console.error("Error fetching CSRF token:", error);
        throw error;
    }
};

const defaultOptions = {
    data: {},
    requestOptions: {
        headers: {},
    },
    notification: {
        show: true,
        success: false,
        failed: true,
    },
};

const useRequest = (initOptions) => {
    const instance = axios.create();
    instance.interceptors.request.use(
        async function (config) {
            if (config.method !== 'get') {
                const csrfToken = await getCsrfToken();
                config.headers['X-CSRF-TOKEN'] = csrfToken;
            }
            return config;
        },
        function (error) {
            return Promise.reject(error);
        }
    );

    const _options = Object.assign({}, defaultOptions, initOptions);

    return async (url = "", method = "get", options) => {
        const mergedOptions = Object.assign({}, _options, options);

        try {
            const response = await instance({
                url,
                method,
                data: method === "get" ? null : mergedOptions.data,
                withCredentials: true,
                ...mergedOptions.requestOptions,
            });
            successRequest(mergedOptions.notification.show && mergedOptions.notification.success, "request_data");
            return response;
        } catch (error) {
            if (error.response) {
                errorResponse(
                    error.response,
                    mergedOptions.notification.show && mergedOptions.notification.failed,
                    "request_data"
                );
            }
            throw error;
        }
    };
};

export default useRequest;
