/**
 * Copyright © Simplyin. All rights reserved.
 *
 * CSRF form_key provider for SimplyIN AJAX requests.
 * Ensures Magento's form_key is included in all POST requests to simplyin/* endpoints.
 *
 * This module sets up a global jQuery AJAX prefilter that automatically adds
 * form_key to request data when the URL matches SimplyIN API endpoints.
 */
define([
    'jquery'
], function ($) {
    'use strict';

    /**
     * Get Magento form_key from the page
     * @returns {string}
     */
    function getFormKey() {
        var formKeyInput = $('input[name="form_key"]');
        if (formKeyInput.length) {
            return formKeyInput.val();
        }

        // Fallback to window.FORM_KEY
        return window.FORM_KEY || '';
    }

    // Register a global AJAX prefilter for SimplyIN endpoints
    $.ajaxPrefilter(function (options) {
        // Only apply to SimplyIN API endpoints
        if (!options.url || options.url.indexOf('simplyin/') === -1) {
            return;
        }

        // Only apply to POST requests with JSON content
        if (options.type && options.type.toUpperCase() !== 'POST') {
            return;
        }

        var formKey = getFormKey();
        if (!formKey) {
            return;
        }

        // Inject form_key into the JSON body
        if (options.contentType && options.contentType.indexOf('application/json') !== -1 && options.data) {
            try {
                var data = JSON.parse(options.data);
                if (typeof data === 'object' && data !== null && !data.form_key) {
                    data.form_key = formKey;
                    options.data = JSON.stringify(data);
                }
            } catch (e) {
                // Not valid JSON — skip
            }
        }
    });

    return {
        getFormKey: getFormKey
    };
});
