/**
 * MIS (webSDK / widget.sovamed.ru) session helpers.
 * Symfony login (ROLE_USER) and MIS session are independent.
 */

function MisSessionError() {
    this.name = 'MisSessionError';
    this.message = 'MIS session is not authenticated';
}

function isAuthenticated(webSDK) {
    return Boolean(webSDK?.data?.user?.authenticated);
}

function ensureAuthenticated(webSDK) {
    return new Promise(function(resolve, reject) {
        if (isAuthenticated(webSDK)) {
            resolve(webSDK);
            return;
        }

        if (typeof webSDK?.isLoggedIn === 'function') {
            webSDK.isLoggedIn(webSDK.sdkOrigin).then(function(result) {
                if (result?.authenticated) {
                    resolve(webSDK);
                    return;
                }
                reject(new MisSessionError());
            }).catch(function() {
                reject(new MisSessionError());
            });
            return;
        }

        reject(new MisSessionError());
    });
}

function removeSdkOverlayModals() {
    document.querySelectorAll('.wr-sdk-widget-modal').forEach(function(modal) {
        modal.remove();
    });
}

/**
 * Move #iframeProtocol from SDK overlay into cabinet bootstrap popup.
 * openConference() must be called without container (SDK applies Guest URL fix).
 */
function mountConferenceInPopup(popup) {
    var iframe = document.getElementById('iframeProtocol');
    var popupBody = popup?.querySelector('#popup-body');

    if (!iframe || !popupBody) {
        return false;
    }

    removeSdkOverlayModals();
    popupBody.innerHTML = '';
    popupBody.appendChild(iframe);
    iframe.style.width = '100%';
    iframe.style.border = 'none';
    iframe.style.height = (window.innerHeight - 100) + 'px';

    var fullScreenBtn = popup.querySelector('.full-scren-modal');
    if (fullScreenBtn) {
        fullScreenBtn.classList.remove('d-none');
    }

    popup.querySelector('.modal-dialog').classList = 'modal-dialog';
    popup.querySelector('.modal-content').classList = 'modal-content';
    popup.querySelector('.modal-title').innerHTML = 'Онлайн консультация';

    if (typeof $ !== 'undefined' && typeof $(popup).modal === 'function') {
        $(popup).modal('show');
    }

    return true;
}

function showMisSessionExpired(popup) {
    if (!popup) {
        window.location.pathname = '/logout';
        return;
    }

    popup.querySelector('.modal-dialog').classList = 'modal-dialog';
    popup.querySelector('.modal-title').innerHTML = 'Сессия виджета истекла';
    popup.querySelector('#popup-body').innerHTML =
        '<p class="mb-3">Личный кабинет открыт, но сессия виджета записи (MIS) истекла. ' +
        'Для оплаты и онлайн-приёма нужно войти снова — повторная авторизация в iframe не требуется.</p>' +
        '<button type="button" class="btn btn-outline-secondary w-100" id="mis-session-relogin">Войти снова</button>';

    popup.querySelector('#mis-session-relogin').addEventListener('click', function() {
        window.location.pathname = '/logout';
    });

    if (typeof $ !== 'undefined' && typeof $(popup).modal === 'function') {
        $(popup).modal('show');
    }
}

function handleMisSessionFailure(popup, error, logContext) {
    if (error instanceof MisSessionError || error?.name === 'MisSessionError') {
        showMisSessionExpired(popup);
        return true;
    }

    return false;
}

module.exports = {
    MisSessionError: MisSessionError,
    isAuthenticated: isAuthenticated,
    ensureAuthenticated: ensureAuthenticated,
    mountConferenceInPopup: mountConferenceInPopup,
    showMisSessionExpired: showMisSessionExpired,
    handleMisSessionFailure: handleMisSessionFailure,
};
