"use strict";
// SPDX-FileCopyrightText: 2026 Catalan Lover <catalanlover@protonmail.com>
// SPDX-FileCopyrightText: 2026 Gnuxie <Gnuxie@protonmail.com>
//
// SPDX-License-Identifier: AFL-3.0
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZeroTouchDeployRoomAccountDataSchema = exports.ZERO_TOUCH_DEPLOY_ROOM_ACCOUNT_DATA_TYPE = void 0;
exports.loadOrCreateZeroTouchDeployRoom = loadOrCreateZeroTouchDeployRoom;
exports.makeZeroTouchDeployRoom = makeZeroTouchDeployRoom;
exports.loadZeroTouchDeployRoomFromConfig = loadZeroTouchDeployRoomFromConfig;
const typescript_result_1 = require("@gnuxie/typescript-result");
const typebox_1 = require("@sinclair/typebox");
const matrix_basic_types_1 = require("@the-draupnir-project/matrix-basic-types");
const matrix_protection_suite_1 = require("matrix-protection-suite");
exports.ZERO_TOUCH_DEPLOY_ROOM_ACCOUNT_DATA_TYPE = "space.draupnir.zero_touch_deploy_room";
exports.ZeroTouchDeployRoomAccountDataSchema = typebox_1.Type.Object({
    room: matrix_protection_suite_1.RoomIDPermalinkSchema,
});
async function loadOrCreateZeroTouchDeployRoom(ZTDRoomAccountData, roomCreator, clientCapabilitiesNegotiation, requestingUserID, draupnirUserID) {
    const loadResult = await ZTDRoomAccountData.requestAccountData();
    if ((0, typescript_result_1.isError)(loadResult)) {
        return loadResult.elaborate("Unable to load zero touch deploy management room from account data");
    }
    if (loadResult.ok !== undefined) {
        return (0, typescript_result_1.Ok)(loadResult.ok.room);
    }
    return await makeZeroTouchDeployRoom(ZTDRoomAccountData, roomCreator, clientCapabilitiesNegotiation, requestingUserID, draupnirUserID);
}
async function makeZeroTouchDeployRoom(ZTDRoomAccountData, roomCreator, clientCapabilitiesNegotiation, requestingUserID, draupnirUserID) {
    const capabilities = await clientCapabilitiesNegotiation.getClientCapabilities();
    if ((0, typescript_result_1.isError)(capabilities)) {
        return capabilities.elaborate("Failed to fetch room versions from client capabilities");
    }
    const defaultRoomVersion = capabilities.ok.capabilities["m.room_versions"].default;
    if (typeof defaultRoomVersion !== "string") {
        return typescript_result_1.ResultError.Result("Client capabilities did not contain a valid default room version");
    }
    const isRoomVersionWithPrivilegedCreators = matrix_protection_suite_1.RoomVersionMirror.isVersionWithPrivilegedCreators(defaultRoomVersion);
    const roomCreateResult = await roomCreator.createRoom({
        preset: "private_chat",
        invite: [requestingUserID],
        name: `${requestingUserID}'s Draupnir`,
        power_level_content_override: isRoomVersionWithPrivilegedCreators
            ? {
                users: {
                    [requestingUserID]: 150,
                },
            }
            : {
                users: {
                    [requestingUserID]: 100,
                    // Give the draupnir a higher PL so that can avoid issues with managing the management room.
                    [draupnirUserID]: 101,
                },
            },
    });
    if ((0, typescript_result_1.isError)(roomCreateResult)) {
        return roomCreateResult.elaborate("Failed to create the zero touch deploy room");
    }
    const storeResult = await ZTDRoomAccountData.storeAccountData({
        room: roomCreateResult.ok,
    });
    if ((0, typescript_result_1.isError)(storeResult)) {
        return storeResult.elaborate("Failed to store the zero touch deploy room account data");
    }
    return roomCreateResult;
}
async function loadZeroTouchDeployRoomFromConfig(configuredZTDRoom, configuredInitialManager, accountData, clientPlatform, clientUserID, options) {
    if (configuredZTDRoom === undefined) {
        if (configuredInitialManager === undefined) {
            return typescript_result_1.ResultError.Result(`If ${options.configuredRoomPropertyName} isn't set, you must set an ${options.configuredInitialManagerPropertyName}`);
        }
        if (!(0, matrix_basic_types_1.isStringUserID)(configuredInitialManager)) {
            return typescript_result_1.ResultError.Result(`${options.configuredInitialManagerPropertyName} is not a StringUserID`);
        }
        return await loadOrCreateZeroTouchDeployRoom(accountData, clientPlatform.toRoomCreator(), clientPlatform.toClientCapabilitiesNegotiation(), configuredInitialManager, clientUserID);
    }
    const configuredZTDRoomReference = (() => {
        if ((0, matrix_basic_types_1.isStringRoomID)(configuredZTDRoom)) {
            return (0, typescript_result_1.Ok)(matrix_basic_types_1.MatrixRoomReference.fromRoomID(configuredZTDRoom));
        }
        else if ((0, matrix_basic_types_1.isStringRoomAlias)(configuredZTDRoom)) {
            return (0, typescript_result_1.Ok)(matrix_basic_types_1.MatrixRoomReference.fromRoomIDOrAlias(configuredZTDRoom));
        }
        else if (!options.allowPermalinkForRoomConfig) {
            return typescript_result_1.ResultError.Result(`${options.configuredRoomPropertyName}: ${configuredZTDRoom} is not a valid room id or alias`);
        }
        else {
            const parseResult = matrix_basic_types_1.MatrixRoomReference.fromPermalink(configuredZTDRoom);
            if ((0, typescript_result_1.isError)(parseResult)) {
                return parseResult.elaborate(`Failed to parse zero touch deploy permalink from ${options.configuredRoomPropertyName}`);
            }
            return parseResult;
        }
    })();
    if ((0, typescript_result_1.isError)(configuredZTDRoomReference)) {
        return configuredZTDRoomReference;
    }
    const ZTDRoomResolveResult = await clientPlatform
        .toRoomResolver()
        .resolveRoom(configuredZTDRoomReference.ok);
    if ((0, typescript_result_1.isError)(ZTDRoomResolveResult)) {
        return ZTDRoomResolveResult.elaborate("Unable to resolve zero touch deploy room");
    }
    const managementRoomJoinResult = await clientPlatform
        .toRoomJoiner()
        .joinRoom(ZTDRoomResolveResult.ok);
    if ((0, typescript_result_1.isError)(managementRoomJoinResult)) {
        return managementRoomJoinResult.elaborate("Unable to join zero touch deploy room");
    }
    return managementRoomJoinResult;
}
//# sourceMappingURL=managedRoomAccountData.js.map