// Copyright (c) 2009-2026 SAP SE, All Rights Reserved

/**
 * @fileoverview This file contains the NWBCHandler module.
 * It handles postMessage requests for NWBC specific dirty state handling.
 */
sap.ui.define([
    "sap/base/Log",
    "sap/base/util/deepClone",
    "sap/base/util/uid",
    "sap/ushell/appIntegration/PostMessageManager",
    "sap/ushell/navigation/DirtyState",
    "sap/ushell/utils"
], (
    Log,
    deepClone,
    uid,
    PostMessageManager,
    DirtyState,
    ushellUtils
) => {
    "use strict";

    const aEventPreprocessor = [
        (oOriginalMessageEvent, oOriginalMessage) => {
            if (oOriginalMessage.action === "pro54_setGlobalDirty") {
                const oMessage = deepClone(oOriginalMessage);
                oMessage.service = "sap.ushell.appIntegration.PostMessageManager.NWBCHandler.pro54_setGlobalDirty";
                delete oMessage.action;

                oMessage.body = oMessage.parameters;
                delete oMessage.parameters;

                if (!oMessage.request_id) {
                    oMessage.request_id = uid();
                }

                if (!oMessage.type) {
                    oMessage.type = "request";
                }

                const oMessageEvent = new MessageEvent("message", {
                    data: JSON.stringify(oMessage),
                    origin: oOriginalMessageEvent.origin,
                    source: oOriginalMessageEvent.source
                });

                return {
                    event: oMessageEvent,
                    message: oMessage
                };
            }
        }
    ];

    const oDistributionPolicies = {};

    const oServiceRequestHandlers = {
        /**
         * There are no known use case of the pro54_setGlobalDirty request, which previously was used to set a
         * global dirty state via localStorage.
         * The handler is kept for backward compatibility with potential use cases, but the implementation now
         * uses the dirty state API instead of the localStorage based behavior.
         *
         * @private
         */
        "sap.ushell.appIntegration.PostMessageManager.NWBCHandler.pro54_setGlobalDirty": {
            async handler (oMessageBody, oApplicationContainer, oMessageEvent) {
                // Map legacy global dirty state string values to boolean
                const bIsDirty = oMessageBody.globalDirty === "DIRTY";
                await DirtyState.setDirtyFlag(bIsDirty);
                Log.debug(
                    `pro54_setGlobalDirty: Set dirty flag to ${bIsDirty} (received: ${oMessageBody.globalDirty})`,
                    null,
                    "sap.ushell.appIntegration.PostMessageHandler.NWBCHandler"
                );
            },
            options: {
                provideApplicationContext: true
            }
        }
    };

    return {
        register () {
            aEventPreprocessor.forEach((fnEventPreprocessor) => {
                PostMessageManager.addEventPreprocessor(fnEventPreprocessor);
            });

            Object.keys(oDistributionPolicies).forEach((sServiceRequest) => {
                const oDistributionPolicy = oDistributionPolicies[sServiceRequest];
                PostMessageManager.setDistributionPolicy(sServiceRequest, oDistributionPolicy);
            });

            Object.keys(oServiceRequestHandlers).forEach((sServiceRequest) => {
                const oHandler = oServiceRequestHandlers[sServiceRequest];
                PostMessageManager.setRequestHandler(sServiceRequest, oHandler.handler, oHandler.options);
            });
        }
    };
});
