(function () {
    'use strict';

    function loginReturnPath() {
        var path = window.location.pathname || '';
        var rel = path;
        var adminIdx = path.indexOf('/admin/');
        if (adminIdx >= 0) {
            rel = path.slice(adminIdx + 7);
        } else {
            rel = path.replace(/^\//, '');
        }
        if (!rel || rel === '') {
            rel = 'index.php';
        }
        rel += window.location.search || '';
        if (/^login\.php/i.test(rel)) {
            return 'index.php';
        }
        return rel;
    }

    function redirectToLogin() {
        window.location.href = 'login.php?next=' + encodeURIComponent(loginReturnPath()) + '&reason=session';
    }

    window.fateAdminRedirectToLogin = redirectToLogin;

    window.fateAdminApiFetch = function (url, options) {
        options = options || {};
        options.credentials = options.credentials || 'same-origin';
        var headers = options.headers || {};
        if (!headers.Accept) {
            headers.Accept = 'application/json';
        }
        options.headers = headers;

        return fetch(url, options).then(function (response) {
            if (response.status === 401) {
                redirectToLogin();
                return Promise.reject(new Error('not_logged_in'));
            }
            return response;
        });
    };
})();
