/**
 * Copyright © Simplyin. All rights reserved.
 *
 * Shared AJAX client for SimplyIN Payment module.
 * Uses Magento's mage/storage and injects the Magento form_key into the JSON request body for
 * CSRF protection (surfaced back into request params and validated server-side by CsrfAwareApiTrait).
 */
define([
    'jquery',
    'mage/storage',
    'mage/url'
], function ($, storage, urlBuilder) {
    'use strict';

    /**
     * Get Magento form_key from the page (hidden input or cookie)
     * @returns {string}
     */
    function getFormKey() {
        // First try the hidden input rendered by Magento on every page
        var formKeyInput = $('input[name="form_key"]');
        if (formKeyInput.length) {
            return formKeyInput.val();
        }

        // Fallback: read from FORM_KEY cookie (set by Magento on page load)
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            if (cookie.indexOf('form_key=') === 0) {
                return cookie.substring('form_key='.length);
            }
        }

        // Last resort: window.FORM_KEY (set by some Magento themes)
        return window.FORM_KEY || '';
    }

    /**
     * Build full URL from relative path
     * @param {string} url
     * @returns {string}
     */
    function buildUrl(url) {
        return urlBuilder.build(url);
    }

    return {
        /**
         * Make a POST request using Magento's mage/storage.
         * mage/storage automatically handles:
         * - X-Requested-With: XMLHttpRequest header
         * - Content-Type: application/json
         * The Magento form_key is injected into the request body below (validated by CsrfAwareApiTrait).
         *
         * @param {string} url - Relative URL path (e.g., 'simplyin/api/checkEmail')
         * @param {Object} data - Request payload
         * @param {Object} [options] - Additional options (unused, kept for backward compat)
         * @returns {jQuery.Deferred} - resolves with parsed JSON response
         */
        post: function (url, data, options) {
            // Clone so the caller's object is never mutated; inject form_key for CSRF protection.
            var payload = (typeof data === 'object' && data !== null) ? $.extend({}, data) : {};
            payload.form_key = getFormKey();

            var fullUrl = buildUrl(url);

            // Use mage/storage.post which handles JSON serialization,
            // Content-Type, X-Requested-With header automatically
            return storage.post(
                fullUrl,
                JSON.stringify(payload),
                true,  // global — show full-screen loader
                'application/json'
            );
        },

        /**
         * Make a silent POST request (no full-screen loader).
         * Used for background polling and fire-and-forget operations.
         *
         * @param {string} url - Relative URL path
         * @param {Object} data - Request payload
         * @returns {jQuery.Deferred}
         */
        postSilent: function (url, data) {
            // Clone so the caller's object is never mutated; inject form_key for CSRF protection.
            var payload = (typeof data === 'object' && data !== null) ? $.extend({}, data) : {};
            payload.form_key = getFormKey();

            var fullUrl = buildUrl(url);

            return storage.post(
                fullUrl,
                JSON.stringify(payload),
                false,  // no global loader
                'application/json'
            );
        },

        /**
         * Get the form_key value (for external use)
         * @returns {string}
         */
        getFormKey: getFormKey,

        /**
         * Build full URL (for external use)
         * @param {string} url
         * @returns {string}
         */
        buildUrl: buildUrl
    };
});
