"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynapseAdminApis = exports.SynapseRoomProperty = void 0;
/**
 * Available properties on a Synapse room listing to order by.
 * @category Admin APIs
 */
var SynapseRoomProperty;
(function (SynapseRoomProperty) {
    SynapseRoomProperty["Name"] = "name";
    SynapseRoomProperty["CanonicalAlias"] = "canonical_alias";
    SynapseRoomProperty["JoinedMembers"] = "joined_members";
    SynapseRoomProperty["JoinedLocalMembers"] = "joined_local_members";
    SynapseRoomProperty["Version"] = "version";
    SynapseRoomProperty["Creator"] = "creator";
    SynapseRoomProperty["Encryption"] = "encryption";
    SynapseRoomProperty["CanFederate"] = "federatable";
    SynapseRoomProperty["IsPublic"] = "public";
    SynapseRoomProperty["JoinRules"] = "join_rules";
    SynapseRoomProperty["GuestAccess"] = "guest_access";
    SynapseRoomProperty["HistoryVisibility"] = "history_visibility";
    SynapseRoomProperty["NumStateEvents"] = "state_events";
})(SynapseRoomProperty = exports.SynapseRoomProperty || (exports.SynapseRoomProperty = {}));
/**
 * Access to various administrative APIs specifically available in Synapse.
 * @category Admin APIs
 */
class SynapseAdminApis {
    constructor(client) {
        this.client = client;
    }
    /**
     * Get information about a user. The client making the request must be an admin user.
     * @param {string} userId The user ID to check.
     * @returns {Promise<SynapseUser>} The resulting Synapse user record
     */
    getUser(userId) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.client.doRequest("GET", "/_synapse/admin/v2/users/" + encodeURIComponent(userId));
        });
    }
    /**
     * Create or update a given user on a Synapse server. The
     * client making the request must be an admin user.
     * @param {string} userId The user ID to check.
     * @param {SynapseUserProperties} opts Options to set when creating or updating the user.
     * @returns {Promise<SynapseUser>} The resulting Synapse user record
     */
    upsertUser(userId, opts = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.client.doRequest("PUT", "/_synapse/admin/v2/users/" + encodeURIComponent(userId), undefined, opts);
        });
    }
    /**
     * Get a list of users registered with Synapse, optionally filtered by some criteria. The
     * client making the request must be an admin user.
     * @param {string} from The token to continue listing users from.
     * @param {number} limit The maximum number of users to request.
     * @param {string} name Optional localpart or display name filter for results.
     * @param {boolean} guests Whether or not to include guest accounts. Default true.
     * @param {boolean} deactivated Whether or not to include deactivated accounts. Default false.
     * @returns {Promise<SynapseUserList>} A batch of user results.
     */
    listUsers(from, limit, name, guests = true, deactivated = false) {
        return __awaiter(this, void 0, void 0, function* () {
            const qs = { guests, deactivated };
            if (from)
                qs['from'] = from;
            if (limit)
                qs['limit'] = limit;
            if (name)
                qs['name'] = name;
            return this.client.doRequest("GET", "/_synapse/admin/v2/users", qs);
        });
    }
    /**
     * Determines if the given user is a Synapse server administrator for this homeserver. The
     * client making the request must be an admin user themselves (check with `isSelfAdmin`)
     * @param {string} userId The user ID to check.
     * @returns {Promise<boolean>} Resolves to true if the user is an admin, false otherwise.
     * Throws if there's an error.
     */
    isAdmin(userId) {
        return __awaiter(this, void 0, void 0, function* () {
            const response = yield this.client.doRequest("GET", `/_synapse/admin/v1/users/${encodeURIComponent(userId)}/admin`);
            return response['admin'] || false;
        });
    }
    /**
     * Determines if the current user is an admin for the Synapse homeserver.
     * @returns {Promise<boolean>} Resolve to true if the user is an admin, false otherwise.
     * Throws if there's an error.
     */
    isSelfAdmin() {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            try {
                return yield this.isAdmin(yield this.client.getUserId());
            }
            catch (e) {
                if (((_a = e === null || e === void 0 ? void 0 : e.body) === null || _a === void 0 ? void 0 : _a.errcode) === 'M_FORBIDDEN') {
                    return false;
                }
                throw e;
            }
        });
    }
    /**
     * Lists the rooms on the server.
     * @param {string} searchTerm A term to search for in the room names
     * @param {string} from A previous batch token to search from
     * @param {number} limit The maximum number of rooms to return
     * @param {SynapseRoomProperty} orderBy A property of rooms to order by
     * @param {boolean} reverseOrder True to reverse the orderBy direction.
     * @returns {Promise<SynapseRoomList>} Resolves to the server's rooms, ordered and filtered.
     */
    listRooms(searchTerm, from, limit, orderBy, reverseOrder = false) {
        return __awaiter(this, void 0, void 0, function* () {
            const params = {};
            if (from)
                params['from'] = from;
            if (limit)
                params['limit'] = limit;
            if (searchTerm)
                params['search_term'] = searchTerm;
            if (orderBy)
                params['order_by'] = orderBy;
            if (reverseOrder) {
                params['dir'] = 'b';
            }
            else {
                params['dir'] = 'f';
            }
            return this.client.doRequest("GET", "/_synapse/admin/v1/rooms", params);
        });
    }
    /**
     * Gets a list of state events in a room.
     * @param {string} roomId The room ID to get state for.
     * @returns {Promise<*[]>} Resolves to the room's state events.
     */
    getRoomState(roomId) {
        return __awaiter(this, void 0, void 0, function* () {
            const r = yield this.client.doRequest("GET", `/_synapse/admin/v1/rooms/${encodeURIComponent(roomId)}/state`);
            return (r === null || r === void 0 ? void 0 : r['state']) || [];
        });
    }
    /**
     * Deletes a room from the server, purging all record of it.
     * @param {string} roomId The room to delete.
     * @returns {Promise} Resolves when complete.
     */
    deleteRoom(roomId) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.client.doRequest("POST", `/_synapse/admin/v1/rooms/${encodeURIComponent(roomId)}/delete`, {}, { purge: true });
        });
    }
}
exports.SynapseAdminApis = SynapseAdminApis;
