"use strict";
// SPDX-FileCopyrightText: 2025 Gnuxie <Gnuxie@protonmail.com>
//
// SPDX-License-Identifier: Apache-2.0
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProtectReplacementRooms = void 0;
const typescript_result_1 = require("@gnuxie/typescript-result");
const matrix_basic_types_1 = require("@the-draupnir-project/matrix-basic-types");
const mps_interface_adaptor_1 = require("@the-draupnir-project/mps-interface-adaptor");
const matrix_protection_suite_1 = require("matrix-protection-suite");
const interface_manager_1 = require("@the-draupnir-project/interface-manager");
const log = new matrix_protection_suite_1.Logger("ProtectReplacementRooms");
class ProtectReplacementRooms {
    managementRoomID;
    roomJoiner;
    roomMessageSender;
    protectedRoomsManager;
    constructor(managementRoomID, roomJoiner, roomMessageSender, protectedRoomsManager) {
        this.managementRoomID = managementRoomID;
        this.roomJoiner = roomJoiner;
        this.roomMessageSender = roomMessageSender;
        this.protectedRoomsManager = protectedRoomsManager;
        // nothing to do.
    }
    handleRoomStateChange(changes) {
        for (const change of changes) {
            if (change.eventType !== "m.room.tombstone") {
                continue;
            }
            switch (change.changeType) {
                case matrix_protection_suite_1.StateChangeType.Introduced:
                case matrix_protection_suite_1.StateChangeType.PartiallyRedacted:
                case matrix_protection_suite_1.StateChangeType.Reintroduced:
                case matrix_protection_suite_1.StateChangeType.SupersededContent:
                    break;
                default:
                    continue;
            }
            if (matrix_protection_suite_1.Value.Check(matrix_protection_suite_1.TombstoneEvent, change.state)) {
                void (0, matrix_protection_suite_1.Task)(this.handleTombstone(change.state), {
                    log,
                });
            }
        }
    }
    async protectReplacementRoom(replacementRoom) {
        const joinResult = await this.roomJoiner.joinRoom(replacementRoom);
        if ((0, typescript_result_1.isError)(joinResult)) {
            return joinResult.elaborate("Failed to join replacement room while following a room upgrade");
        }
        const protectResult = await this.protectedRoomsManager.addRoom(replacementRoom);
        if ((0, typescript_result_1.isError)(protectResult)) {
            return protectResult.elaborate("Failed to protect the replacement room while following a room upgrade");
        }
        return (0, typescript_result_1.Ok)(undefined);
    }
    async notifyManagementRoomOfUpgrade(event, replacementRoom) {
        return (await (0, mps_interface_adaptor_1.sendMatrixEventsFromDeadDocument)(this.roomMessageSender, this.managementRoomID, interface_manager_1.DeadDocumentJSX.JSXFactory("root", null,
            interface_manager_1.DeadDocumentJSX.JSXFactory("h4", null,
                "The room",
                " ",
                (0, mps_interface_adaptor_1.renderRoomPill)(matrix_basic_types_1.MatrixRoomReference.fromRoomID(event.room_id)),
                " has been upgraded to ",
                (0, mps_interface_adaptor_1.renderRoomPill)(replacementRoom),
                " (",
                interface_manager_1.DeadDocumentJSX.JSXFactory("code", null, replacementRoom.toRoomIDOrAlias()),
                ")"),
            "The replacement room is now protected."), {}));
    }
    async reportRoomUpgradeError(error, event, replacementRoom) {
        return (await (0, mps_interface_adaptor_1.sendMatrixEventsFromDeadDocument)(this.roomMessageSender, this.managementRoomID, interface_manager_1.DeadDocumentJSX.JSXFactory("root", null,
            interface_manager_1.DeadDocumentJSX.JSXFactory("details", null,
                interface_manager_1.DeadDocumentJSX.JSXFactory("summary", null,
                    "Failed to protect the replacement room",
                    " ",
                    (0, mps_interface_adaptor_1.renderRoomPill)(replacementRoom),
                    " (",
                    replacementRoom.toRoomIDOrAlias(),
                    ") after upgrading from",
                    " ",
                    (0, mps_interface_adaptor_1.renderRoomPill)(matrix_basic_types_1.MatrixRoomReference.fromRoomID(event.room_id)),
                    " -",
                    " ",
                    (0, mps_interface_adaptor_1.renderOutcome)(false)),
                error.mostRelevantElaboration,
                (0, mps_interface_adaptor_1.renderDetailsNotice)(error),
                (0, mps_interface_adaptor_1.renderElaborationTrail)(error),
                (0, mps_interface_adaptor_1.renderExceptionTrail)(error))), {}));
    }
    async handleTombstone(event) {
        if (!this.protectedRoomsManager.isProtectedRoom(event.room_id)) {
            return (0, typescript_result_1.Ok)(undefined);
        }
        if (event.content.replacement_room === undefined) {
            // No replacement room specified, nothing to do.
            return (0, typescript_result_1.Ok)(undefined);
        }
        const replacementRoom = new matrix_basic_types_1.MatrixRoomID(event.content.replacement_room, [
            (0, matrix_basic_types_1.userServerName)(event.sender),
        ]);
        const upgradeResult = await this.protectReplacementRoom(replacementRoom);
        if ((0, typescript_result_1.isError)(upgradeResult)) {
            void (0, matrix_protection_suite_1.Task)(this.reportRoomUpgradeError(upgradeResult.error, event, replacementRoom), { log });
        }
        else {
            void (0, matrix_protection_suite_1.Task)(this.notifyManagementRoomOfUpgrade(event, replacementRoom), {
                log,
            });
        }
        return upgradeResult;
    }
}
exports.ProtectReplacementRooms = ProtectReplacementRooms;
//# sourceMappingURL=ProtectReplacementRooms.js.map