var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import WorkspaceType from "../../../Types/Workspace/WorkspaceType";
import SlackWorkspace from "./Slack/Slack";
import MicrosoftTeamsUtil from "./MicrosoftTeams/MicrosoftTeams";
import BadDataException from "../../../Types/Exception/BadDataException";
import logger from "../Logger";
import WorkspaceProjectAuthTokenService from "../../Services/WorkspaceProjectAuthTokenService";
import WorkspaceUserAuthTokenService from "../../Services/WorkspaceUserAuthTokenService";
import UserService from "../../Services/UserService";
import CaptureSpan from "../Telemetry/CaptureSpan";
import OneUptimeDate from "../../../Types/Date";
export default class WorkspaceUtil {
    static async getMessageBlocksByMarkdown(data) {
        const workspaceTypes = this.getAllWorkspaceTypes();
        const messageBlocksByWorkspaceType = [];
        for (const workspaceType of workspaceTypes) {
            let userStringToAppend = "";
            if (data.userId) {
                const workspaceUserToken = await WorkspaceUserAuthTokenService.getUserAuth({
                    userId: data.userId,
                    workspaceType: workspaceType,
                    projectId: data.projectId,
                });
                if (workspaceUserToken && workspaceUserToken.workspaceUserId) {
                    const projectAuthToken = await WorkspaceProjectAuthTokenService.getProjectAuth({
                        projectId: data.projectId,
                        workspaceType: workspaceType,
                    });
                    if (!projectAuthToken || !projectAuthToken.authToken) {
                        userStringToAppend = "";
                    }
                    else {
                        const workspaceUsername = await this.getUserNameFromWorkspace({
                            userId: workspaceUserToken.workspaceUserId,
                            workspaceType: workspaceType,
                            authToken: projectAuthToken.authToken,
                            projectId: data.projectId,
                        });
                        if (!workspaceUsername) {
                            const userstring = await UserService.getUserMarkdownString({
                                userId: data.userId,
                                projectId: data.projectId,
                            });
                            userStringToAppend = `${userstring} `;
                        }
                        userStringToAppend = `@${workspaceUsername} `;
                    }
                }
                else {
                    const userstring = await UserService.getUserMarkdownString({
                        userId: data.userId,
                        projectId: data.projectId,
                    });
                    userStringToAppend = `${userstring} `;
                }
            }
            messageBlocksByWorkspaceType.push({
                workspaceType: workspaceType,
                messageBlocks: [
                    {
                        _type: "WorkspacePayloadMarkdown",
                        text: userStringToAppend + data.markdown,
                    },
                ],
            });
        }
        return messageBlocksByWorkspaceType;
    }
    static getAllWorkspaceTypes() {
        const workspaceTypes = [];
        for (const workspaceType in WorkspaceType) {
            workspaceTypes.push(workspaceType);
        }
        return workspaceTypes;
    }
    static getWorkspaceTypeUtil(workspaceType) {
        if (workspaceType === WorkspaceType.Slack) {
            return SlackWorkspace;
        }
        if (workspaceType === WorkspaceType.MicrosoftTeams) {
            return MicrosoftTeamsUtil;
        }
        throw new BadDataException(`Workspace type ${workspaceType} is not supported`);
    }
    static async getUserNameFromWorkspace(data) {
        const userName = await WorkspaceUtil.getWorkspaceTypeUtil(data.workspaceType).getUsernameFromUserId({
            userId: data.userId,
            authToken: data.authToken,
            projectId: data.projectId,
        });
        return userName;
    }
    static async postMessageToAllWorkspaceChannelsAsBot(data) {
        var _a;
        const workspaceLogAttributes = {
            projectId: (_a = data.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
        };
        logger.debug("postToWorkspaceChannels called with data:", workspaceLogAttributes);
        logger.debug(JSON.stringify(data, null, 2), workspaceLogAttributes);
        const responses = [];
        for (const messagePayloadByWorkspace of data.messagePayloadsByWorkspace) {
            const projectAuthToken = await WorkspaceProjectAuthTokenService.getProjectAuth({
                projectId: data.projectId,
                workspaceType: messagePayloadByWorkspace.workspaceType,
            });
            if (!projectAuthToken) {
                responses.push({
                    workspaceType: messagePayloadByWorkspace.workspaceType,
                    threads: [],
                });
                continue;
            }
            const workspaceType = messagePayloadByWorkspace.workspaceType;
            let botUserId = undefined;
            if (workspaceType === WorkspaceType.Slack) {
                botUserId = projectAuthToken.miscData.botUserId;
                if (!botUserId) {
                    responses.push({
                        workspaceType: workspaceType,
                        threads: [],
                    });
                    continue;
                }
            }
            if (!projectAuthToken.authToken) {
                responses.push({
                    workspaceType: workspaceType,
                    threads: [],
                });
                continue;
            }
            const result = await WorkspaceUtil.getWorkspaceTypeUtil(workspaceType).sendMessage({
                userId: botUserId || "",
                authToken: projectAuthToken.authToken,
                projectId: data.projectId,
                workspaceMessagePayload: messagePayloadByWorkspace,
            });
            responses.push(result);
        }
        logger.debug("Message posted to workspace channels successfully", workspaceLogAttributes);
        logger.debug("Returning thread IDs", workspaceLogAttributes);
        logger.debug(JSON.stringify(responses, null, 2), workspaceLogAttributes);
        return responses;
    }
    static async postToWorkspaceChannels(data) {
        var _a;
        const postLogAttributes = {
            projectId: (_a = data.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
        };
        logger.debug("postToWorkspaceChannels called with data:", postLogAttributes);
        logger.debug(data, postLogAttributes);
        const result = await WorkspaceUtil.getWorkspaceTypeUtil(data.workspaceType).sendMessage({
            userId: data.workspaceUserId,
            workspaceMessagePayload: data.workspaceMessagePayload,
            authToken: data.projectOrUserAuthTokenForWorkspace,
            projectId: data.projectId,
        });
        logger.debug("Message posted to workspace channels successfully", postLogAttributes);
        logger.debug("Returning thread IDs", postLogAttributes);
        logger.debug(result, postLogAttributes);
        return result;
    }
    static async getChannelMessages(params) {
        var _a, _b;
        switch (params.workspaceType) {
            case WorkspaceType.Slack: {
                const slackParams = {
                    channelId: params.channelId,
                    authToken: params.authToken,
                };
                if (params.limit !== undefined) {
                    slackParams.limit = params.limit;
                }
                if (params.oldestTimestamp) {
                    slackParams.oldestTimestamp = params.oldestTimestamp;
                }
                return await SlackWorkspace.getChannelMessages(slackParams);
            }
            case WorkspaceType.MicrosoftTeams: {
                if (!params.teamId) {
                    logger.error("Team ID is required for Microsoft Teams channel messages", { projectId: (_a = params.projectId) === null || _a === void 0 ? void 0 : _a.toString() });
                    return [];
                }
                const teamsParams = {
                    channelId: params.channelId,
                    teamId: params.teamId,
                    projectId: params.projectId,
                };
                if (params.limit !== undefined) {
                    teamsParams.limit = params.limit;
                }
                if (params.oldestTimestamp) {
                    teamsParams.oldestTimestamp = params.oldestTimestamp;
                }
                return await MicrosoftTeamsUtil.getChannelMessages(teamsParams);
            }
            default:
                logger.debug(`Unsupported workspace type for channel messages: ${params.workspaceType}`, { projectId: (_b = params.projectId) === null || _b === void 0 ? void 0 : _b.toString() });
                return [];
        }
    }
    static formatMessagesAsContext(messages, options) {
        var _a, _b;
        const includeTimestamp = (_a = options === null || options === void 0 ? void 0 : options.includeTimestamp) !== null && _a !== void 0 ? _a : true;
        const includeUsername = (_b = options === null || options === void 0 ? void 0 : options.includeUsername) !== null && _b !== void 0 ? _b : true;
        const maxLength = (options === null || options === void 0 ? void 0 : options.maxLength) || 50000;
        let context = "";
        for (const msg of messages) {
            let line = "";
            if (includeTimestamp) {
                const dateStr = OneUptimeDate.getDateAsFormattedString(msg.timestamp);
                line += `[${dateStr}] `;
            }
            if (includeUsername && msg.username) {
                line += `${msg.username}: `;
            }
            else if (includeUsername && msg.userId) {
                line += `User ${msg.userId}: `;
            }
            line += msg.text;
            line += "\n";
            // Check if adding this line would exceed max length
            if (context.length + line.length > maxLength) {
                context += "\n... (messages truncated due to length)";
                break;
            }
            context += line;
        }
        return context.trim();
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], WorkspaceUtil, "getMessageBlocksByMarkdown", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Array)
], WorkspaceUtil, "getAllWorkspaceTypes", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Object)
], WorkspaceUtil, "getWorkspaceTypeUtil", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], WorkspaceUtil, "getUserNameFromWorkspace", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], WorkspaceUtil, "postMessageToAllWorkspaceChannelsAsBot", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], WorkspaceUtil, "postToWorkspaceChannels", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], WorkspaceUtil, "getChannelMessages", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Array, Object]),
    __metadata("design:returntype", String)
], WorkspaceUtil, "formatMessagesAsContext", null);
//# sourceMappingURL=Workspace.js.map