/**
 * Javascript API helper functions
 *
 * @since 3.0.0
 * @author Sarath GP <sarath.gp@mozilor.com>
 *
 */

import apiFetch from '@wordpress/api-fetch'
apiFetch.use(apiFetch.createNonceMiddleware(window.wccGlobals.api.nonce))
apiFetch.use(apiFetch.createRootURLMiddleware(window.wccGlobals.api.base))

// Setup middlewares.
var wccRest = {
    post: function (options) {
        options = options || {};
        options.method = 'POST';

        // Handle FormData specially
        if (options.data instanceof FormData) {
            // Don't modify FormData
            options.body = options.data;
            delete options.data; // Remove data property as we're using body
        } else {
            // Handle regular data as before
            if (options.params) {
                const urlParams = new URLSearchParams(Object.entries(options.params));
                options.path = options.path + '?' + urlParams;
            }
        }

        try {
            return apiFetch(options);
        } catch (error) {
            return error;
        }
    },
    get: function (options) {

        options = options || {}
        options.method = 'GET'
        // Add param support.
        if (options.params) {
            const urlParams = new URLSearchParams(Object.entries(options.params))
            options.path = options.path + '?' + urlParams
        }
        try {
            return apiFetch(options);
        } catch (error) {
            return error;
        }
    },
    put: function (options) {
        options = options || {}
        options.method = 'PUT'
        if (options.params) {
            const urlParams = new URLSearchParams(Object.entries(options.params))
            options.path = options.path + '?' + urlParams
        }
        try {
            return apiFetch(options);
        } catch (error) {
            return error;
        }
    },
    delete: function (options) {

        options = options || {}
        options.method = 'DELETE'

        try {
            return apiFetch(options);
        } catch (error) {
            return error;
        }
    },

}
export default wccRest;