/**
 * Server-side cache invalidation for source (SQL) and Sitefinity targets.
 * Loaded before connection dialogs and platform apps.
 */
(function (global) {
    'use strict';

    function parseJsonBody(res) {
        return res.text().then(function (t) {
            if (!t) return null;
            try {
                return JSON.parse(t);
            } catch (e) {
                return null;
            }
        });
    }

    global.ChameleonCacheRefresh = global.ChameleonCacheRefresh || {};

    /**
     * @param {number} connectionId
     * @param {string} platformType Sitecore | Umbraco | SharePoint | Custom
     */
    global.ChameleonCacheRefresh.invalidateSourceCaches = function (connectionId, platformType) {
        var id = connectionId != null ? Number(connectionId) : NaN;
        if (!id || id <= 0) return Promise.reject(new Error('Invalid connection id'));
        var plat = (platformType || '').trim();
        return fetch('/api/ContentTree/InvalidateRepositoryCaches', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ connectionId: id, platformType: plat })
        }).then(function (res) {
            return parseJsonBody(res).then(function (j) {
                if (!res.ok || !j || j.success === false)
                    throw new Error((j && (j.message || j.Message)) || 'Could not reset server cache');
            });
        });
    };

    /** @param {number} connectionId */
    global.ChameleonCacheRefresh.invalidateSitefinityCaches = function (connectionId) {
        var id = connectionId != null ? Number(connectionId) : NaN;
        if (!id || id <= 0) return Promise.reject(new Error('Invalid connection id'));
        return fetch('/api/SitefinityConnectivity/InvalidateConnectionCaches', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ connectionId: id })
        }).then(function (res) {
            return parseJsonBody(res).then(function (j) {
                if (!res.ok || !j || j.success === false)
                    throw new Error((j && (j.message || j.Message)) || 'Could not reset server cache');
            });
        });
    };
})(typeof window !== 'undefined' ? window : globalThis);
