define([
    'jquery',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/url-builder',
    'mage/storage'
], function ($, quote, urlBuilder, storage) {
    'use strict';

    return function (shippingDate, shippingMessage) {
        var serviceUrl;
        var payload;

        if (!quote.isVirtual()) {
            serviceUrl = urlBuilder.createUrl('/carts/mine/shipping-fields', {});
            payload = {
                cartId: quote.getQuoteId(),
                shippingDate: shippingDate,
                shippingMessage: shippingMessage
            };

            console.log('📤 Saving shipping fields via custom endpoint:', payload);

            return storage.post(
                serviceUrl,
                JSON.stringify(payload)
            ).done(function (response) {
                console.log('✅ Shipping fields saved successfully');
            }).fail(function (response) {
                console.error('❌ Failed to save shipping fields:', response);
            });
        }
    };
});
