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 ObjectID from "../../../../../Types/ObjectID";
import WorkspaceProjectAuthTokenService from "../../../../Services/WorkspaceProjectAuthTokenService";
import WorkspaceType from "../../../../../Types/Workspace/WorkspaceType";
import logger from "../../../Logger";
import CaptureSpan from "../../../Telemetry/CaptureSpan";
import WorkspaceUserAuthTokenService from "../../../../Services/WorkspaceUserAuthTokenService";
import BadDataException from "../../../../../Types/Exception/BadDataException";
export default class MicrosoftTeamsAuthAction {
    static async isAuthorized(data) {
        const req = data.req;
        let payload = {};
        let tenantId = "";
        try {
            payload = req.body;
            logger.debug("Microsoft Teams payload received:");
            logger.debug(payload);
        }
        catch (error) {
            logger.debug("Failed to parse Microsoft Teams payload:");
            logger.debug(error);
            return {
                isAuthorized: false,
                projectId: new ObjectID(""),
                authToken: "",
                payloadType: "unknown",
                tenantId: tenantId,
            };
        }
        // Microsoft Teams sends different types of activities
        const activityType = payload["type"];
        const from = payload["from"];
        const conversation = payload["conversation"];
        const channelData = payload["channelData"];
        let teamId = "";
        let channelId = "";
        let userId = "";
        // Extract team and channel information
        if (channelData && channelData["team"]) {
            teamId = channelData["team"]["id"];
        }
        if (conversation && conversation["id"]) {
            // For channel messages, conversation ID contains channel info
            channelId = conversation["id"];
        }
        if (from && from["id"]) {
            userId = from["id"];
        }
        if (channelData && channelData["tenant"]) {
            tenantId = channelData["tenant"]["id"];
        }
        // Handle different activity types
        if (activityType === "installationUpdate") {
            // Bot was installed or uninstalled
            const action = payload["action"];
            if (action === "remove") {
                return {
                    isAuthorized: true,
                    projectId: new ObjectID(""), // We'll need to find the project
                    authToken: "",
                    payloadType: "app_uninstall",
                    teamId: teamId,
                    tenantId: tenantId,
                };
            }
        }
        // Find the project associated with this team
        if (!teamId) {
            logger.debug("No team ID found in payload", {
                tenantId: tenantId,
            });
            return {
                isAuthorized: false,
                projectId: new ObjectID(""),
                authToken: "",
                payloadType: activityType,
                tenantId: tenantId,
            };
        }
        let projectAuthToken = null;
        try {
            // Find project auth token by checking if miscData contains the teamId
            projectAuthToken = await WorkspaceProjectAuthTokenService.findOneBy({
                query: {
                    workspaceType: WorkspaceType.MicrosoftTeams,
                    workspaceProjectId: tenantId,
                },
                select: {
                    _id: true,
                    projectId: true,
                    authToken: true,
                    miscData: true,
                },
                props: {
                    isRoot: true,
                },
            });
        }
        catch (error) {
            logger.debug("Error finding project auth token:", {
                teamId: teamId,
                tenantId: tenantId,
            });
            logger.debug(error);
            return {
                isAuthorized: false,
                projectId: new ObjectID(""),
                authToken: "",
                payloadType: activityType,
                tenantId: tenantId,
            };
        }
        if (!projectAuthToken) {
            logger.debug(`No project auth token found for team: ${teamId}`, {
                teamId: teamId,
                tenantId: tenantId,
            });
            return {
                isAuthorized: false,
                projectId: new ObjectID(""),
                authToken: "",
                payloadType: activityType,
                tenantId: tenantId,
            };
        }
        // Parse actions from the payload
        const actions = [];
        if (activityType === "invoke") {
            // Handle adaptive card button clicks
            const value = payload["value"];
            if (value && value["action"]) {
                actions.push({
                    actionType: value["action"],
                    actionValue: value["actionValue"],
                });
            }
        }
        else if (activityType === "message") {
            // Handle text messages to the bot
            const text = payload["text"] || "";
            if (text.toLowerCase().includes("help")) {
                actions.push({
                    actionType: "help",
                });
            }
        }
        return {
            isAuthorized: true,
            projectId: projectAuthToken.projectId,
            authToken: projectAuthToken.authToken,
            payloadType: activityType,
            actions: actions,
            userId: userId,
            teamId: teamId,
            tenantId: tenantId,
            channelId: channelId,
            messageId: payload["id"],
            payload: payload,
        };
    }
    static async getOneUptimeUserIdFromTeamsUserId(data) {
        /*
         * Find a OneUptime user associated with this Teams user ID using WorkspaceUserAuthToken table
         * This table is populated when users authenticate with Microsoft Teams through the OAuth flow
         */
        try {
            // Look up the user in the WorkspaceUserAuthToken table
            const workspaceUserAuthToken = await WorkspaceUserAuthTokenService.findOneBy({
                query: {
                    workspaceUserId: data.teamsUserId,
                    projectId: data.projectId,
                    workspaceType: WorkspaceType.MicrosoftTeams,
                },
                select: {
                    userId: true,
                },
                props: {
                    isRoot: true,
                },
            });
            if (workspaceUserAuthToken && workspaceUserAuthToken.userId) {
                logger.debug("Found OneUptime user for Teams user: " + data.teamsUserId, {
                    projectId: data.projectId.toString(),
                    workspaceUserId: data.teamsUserId,
                });
                return workspaceUserAuthToken.userId;
            }
            throw new BadDataException("No OneUptime user linked to this Microsoft Teams user. Please authenticate with Microsoft Teams.");
        }
        catch (error) {
            logger.error("Error finding OneUptime user for Teams user: " + data.teamsUserId, {
                projectId: data.projectId.toString(),
                workspaceUserId: data.teamsUserId,
            });
            logger.error(error);
            throw error;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MicrosoftTeamsAuthAction, "isAuthorized", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MicrosoftTeamsAuthAction, "getOneUptimeUserIdFromTeamsUserId", null);
//# sourceMappingURL=Auth.js.map