// Copyright (c) 2009-2026 SAP SE, All Rights Reserved
/**
 * @fileoverview This module provides a function <code>load</code> for loading the core-min-x resource bundles.
 * Besides that, <code>loaded</code> indicates if core-min bundles have been loaded.
 *
 * @deprecated since 1.136.0. The usage of custom preload bundles has been abandoned in favor of the standard SAPUI5 loading.
 */
sap.ui.define([
    "sap/base/Log",
    "sap/ushell/base/requireAsync",
    "sap/ushell/bootstrap/Config"
], (
    Log,
    requireAsync,
    BootstrapConfig
) => {
    "use strict";

    const sUiDebugKey = "sap-ui-debug";

    class CoreMinLoader {
        isDebug () {
            let sStoredSapUiDebugValue;
            let bDebugSources = /[?&]sap-ui-debug=(true|x|X)(&|$)/.test(this.getWindowLocationSearch());

            if (!bDebugSources) {
                try {
                    sStoredSapUiDebugValue = window.localStorage.getItem(sUiDebugKey);
                    bDebugSources = !!sStoredSapUiDebugValue && /^(true|x|X)$/.test(sStoredSapUiDebugValue);
                } catch { /* fail silently */ }
            }

            return bDebugSources;
        }

        async load () {
            const oPreloadBundleConfig = BootstrapConfig.getCustomPreloads();

            if (typeof (oPreloadBundleConfig) !== "object") {
                //  bundle config is mandatory for cdm bootstrap - fail fast
                throw new Error("Mandatory preload bundle configuration is not provided");
            }

            if (this.isDebug() || oPreloadBundleConfig.enabled === false) {
                if (oPreloadBundleConfig.enabled === false) {
                    Log.error("Disabling the custom preload bundles is not yet supported and might fail.");
                }

                // If pure debug mode is turned on (sap-ui-debug=(true|x|X)), it's only
                // needed to require the Core and boot the core because the minified preload
                // modules should be loaded with the single -dbg versions.
                const [Core] = await requireAsync(["sap/ui/core/Core"]);
                Core.boot();

                // do not continue with bundle loading
                return;
            }

            if (oPreloadBundleConfig.enabled === false) {
                throw new Error("Disabling the custom preload bundles is not yet supported");
            }

            const aCoreResources = oPreloadBundleConfig && oPreloadBundleConfig.coreResources || [];
            aCoreResources.forEach((sBundleName) => {
                this.#loadScript(sap.ui.require.toUrl(sBundleName));
            });
        }

        /**
         * Load the js script by adding the script tag to the head.
         * The script tag is added with async attribute.
         *
         * @param {string} sFilePath The src attribute for the script.
         * @param {string} [sId] The id attribute for the script. Not set, if not defined.
         * @param {boolean} [bIsDefer] The defer attribute for the script. Not set, if not defined.
         * @param {boolean} [bAsync=false] The async attribute for the script.
         *
         * @returns {Promise} Result promise is resolved if script was loaded successfully
         *
         * @private
         */
        #loadScript (sFilePath, sId, bIsDefer, bAsync) {
            return new Promise((resolve, reject) => {
                function listener (oEvent) {
                    oEvent.target.removeEventListener("load", listener);
                    oEvent.target.removeEventListener("error", listener);
                    if (oEvent.type === "error") {
                        reject(new Error(`Failed to load script: ${sFilePath}`));
                    }
                    resolve();
                }

                const oScriptElement = document.createElement("script");
                oScriptElement.src = sFilePath;
                oScriptElement.async = !!bAsync;
                oScriptElement.addEventListener("load", listener);
                oScriptElement.addEventListener("error", listener);
                if (sId) {
                    oScriptElement.id = sId;
                }
                if (bIsDefer) {
                    oScriptElement.setAttribute("defer", "");
                }

                document.head.appendChild(oScriptElement);
            });
        }

        getWindowLocationSearch () {
            return window.location.search;
        }
    }

    return new CoreMinLoader();
});
