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 WorkspaceUserAuthTokenService from "../../../../Services/WorkspaceUserAuthTokenService";
import SlackUtil from "../Slack";
import SlackActionType from "./ActionTypes";
import WorkspaceProjectAuthTokenService from "../../../../Services/WorkspaceProjectAuthTokenService";
import logger from "../../../Logger";
import CaptureSpan from "../../../Telemetry/CaptureSpan";
const slackActionTypesThatDoNotRequireUserSlackAccountToBeConnectedToOneUptime = [
    /*
     * anyone in the company can create incident.
     * regardless of whether they are connected to OneUptime or not.
     */
    SlackActionType.NewIncident,
    SlackActionType.SubmitNewIncident,
    SlackActionType.ViewIncident,
    // Alerts
    SlackActionType.ViewAlert,
    // scheduled maintenance
    SlackActionType.ViewScheduledMaintenance,
];
export default class SlackAuthAction {
    static async isAuthorized(data) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        const { req } = data;
        logger.debug("Starting Slack request authorization");
        logger.debug(`Request body: `);
        logger.debug(req.body);
        let payload = req.body;
        if (payload["payload"] && typeof payload["payload"] === "string") {
            payload = JSON.parse(payload["payload"]);
        }
        logger.debug(`Payload: `);
        logger.debug(payload);
        let slackUserId = (_a = payload["user"]) === null || _a === void 0 ? void 0 : _a["id"];
        let slackTeamId = (_b = payload["team"]) === null || _b === void 0 ? void 0 : _b["id"];
        // if there are no actions then return.
        if ((!payload["actions"] || payload["actions"].length === 0) &&
            payload["type"] !== "view_submission" &&
            payload["type"] !== "shortcut" &&
            payload["type"] !== "app_uninstalled" &&
            !payload["command"]) {
            logger.debug("No actions found in payload. Returning unauthorized.");
            return {
                isAuthorized: false,
            };
        }
        const actions = (payload["actions"] || []).map((action) => {
            return {
                actionValue: action["value"],
                actionType: action["action_id"],
            };
        });
        let slackChannelId = (_c = payload === null || payload === void 0 ? void 0 : payload["channel"]) === null || _c === void 0 ? void 0 : _c["id"];
        if (!slackChannelId) {
            slackChannelId = payload === null || payload === void 0 ? void 0 : payload["channel_id"];
        }
        const slackMessageId = (_d = payload === null || payload === void 0 ? void 0 : payload["message"]) === null || _d === void 0 ? void 0 : _d["ts"];
        const slackUserFullName = (_e = payload === null || payload === void 0 ? void 0 : payload["user"]) === null || _e === void 0 ? void 0 : _e["name"];
        let slackUsername = (_f = payload === null || payload === void 0 ? void 0 : payload["user"]) === null || _f === void 0 ? void 0 : _f["username"];
        if (payload["user_id"]) {
            slackUserId = payload["user_id"];
        }
        if (payload["user_name"]) {
            slackUsername = payload["user_name"];
        }
        if (payload["team_id"]) {
            slackTeamId = payload["team_id"];
        }
        const triggerId = payload === null || payload === void 0 ? void 0 : payload["trigger_id"];
        const projectAuth = await WorkspaceProjectAuthTokenService.findOneBy({
            query: {
                workspaceProjectId: slackTeamId,
            },
            select: {
                projectId: true,
                authToken: true,
                miscData: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!projectAuth) {
            return {
                isAuthorized: false,
            };
        }
        const projectId = projectAuth.projectId;
        if (!projectId) {
            logger.debug("Project ID not found in project auth. Returning unauthorized.");
            return {
                isAuthorized: false,
            };
        }
        const userAuth = await WorkspaceUserAuthTokenService.findOneBy({
            query: {
                workspaceUserId: slackUserId,
                projectId: projectId,
            },
            select: {
                userId: true,
                authToken: true,
            },
            props: {
                isRoot: true,
            },
        });
        const botUserId = (_g = projectAuth.miscData) === null || _g === void 0 ? void 0 : _g.botUserId;
        const userId = userAuth === null || userAuth === void 0 ? void 0 : userAuth.userId;
        const view = payload["view"] || undefined;
        let viewValues = {};
        if (view) {
            viewValues = SlackUtil.getValuesFromView({
                view: view,
            });
            // add actionId and actionValue
            const action = {
                // view callbackId
                actionType: view["callback_id"],
                // private metadata
                actionValue: (_h = view["private_metadata"]) === null || _h === void 0 ? void 0 : _h.toString(),
            };
            actions.push(action);
            logger.debug("View values: ");
            logger.debug(viewValues);
            logger.debug("Actions: ");
            logger.debug(actions);
        }
        if (payload["callback_id"]) {
            const action = {
                actionType: payload["callback_id"],
            };
            actions.push(action);
        }
        const command = payload["command"];
        const commandText = payload["text"];
        // add command to actions.
        if (command) {
            const action = {
                actionType: command,
                actionValue: commandText,
            };
            actions.push(action);
        }
        // check if all the actions are authed.
        if (!userId) {
            for (const action of actions) {
                if (action.actionType &&
                    !slackActionTypesThatDoNotRequireUserSlackAccountToBeConnectedToOneUptime.includes(action.actionType)) {
                    const markdwonPayload = {
                        _type: "WorkspacePayloadMarkdown",
                        text: `@${slackUsername}, Unfortunately your slack account is not connected to OneUptime. Please log into your OneUptime account, click on User Settings and then connect your Slack account. `,
                    };
                    await SlackUtil.sendDirectMessageToUser({
                        authToken: projectAuth.authToken,
                        workspaceUserId: slackUserId,
                        messageBlocks: [markdwonPayload],
                    });
                    // clear response.
                    logger.debug("User auth not found. Returning unauthorized.");
                    return {
                        isAuthorized: false,
                    };
                }
            }
        }
        const slackRequest = {
            isAuthorized: true,
            slackUserId: slackUserId,
            payloadType: payload["type"],
            userId: userId,
            projectId: projectId,
            projectAuthToken: projectAuth.authToken,
            userAuthToken: userAuth === null || userAuth === void 0 ? void 0 : userAuth.authToken,
            botUserId: botUserId,
            slackChannelId: slackChannelId,
            slackUsername: slackUsername,
            slackMessageId: slackMessageId,
            slackUserFullName: slackUserFullName,
            actions: actions,
            triggerId: triggerId,
            view: view,
            viewValues: viewValues,
        };
        logger.debug("Slack request authorized successfully", {
            projectId: projectId.toString(),
        });
        logger.debug("Slack request: ");
        logger.debug(slackRequest);
        return slackRequest;
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], SlackAuthAction, "isAuthorized", null);
//# sourceMappingURL=Auth.js.map