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 Response from "../../../Response";
import MicrosoftTeamsAuthAction from "./Auth";
import { MicrosoftTeamsAlertEpisodeActionType } from "./ActionTypes";
import logger from "../../../Logger";
import ObjectID from "../../../../../Types/ObjectID";
import AlertEpisodeService from "../../../../Services/AlertEpisodeService";
import CaptureSpan from "../../../Telemetry/CaptureSpan";
import AlertEpisodeInternalNoteService from "../../../../Services/AlertEpisodeInternalNoteService";
import OnCallDutyPolicyService from "../../../../Services/OnCallDutyPolicyService";
import AlertStateService from "../../../../Services/AlertStateService";
import UserNotificationEventType from "../../../../../Types/UserNotification/UserNotificationEventType";
export default class MicrosoftTeamsAlertEpisodeActions {
    static isAlertEpisodeAction(data) {
        return (data.actionType.includes("AlertEpisode") ||
            data.actionType ===
                MicrosoftTeamsAlertEpisodeActionType.AckAlertEpisode ||
            data.actionType ===
                MicrosoftTeamsAlertEpisodeActionType.ResolveAlertEpisode ||
            data.actionType ===
                MicrosoftTeamsAlertEpisodeActionType.ViewAlertEpisode ||
            data.actionType ===
                MicrosoftTeamsAlertEpisodeActionType.AlertEpisodeCreated ||
            data.actionType ===
                MicrosoftTeamsAlertEpisodeActionType.AlertEpisodeStateChanged ||
            data.actionType ===
                MicrosoftTeamsAlertEpisodeActionType.ViewAddAlertEpisodeNote ||
            data.actionType ===
                MicrosoftTeamsAlertEpisodeActionType.SubmitAlertEpisodeNote ||
            data.actionType ===
                MicrosoftTeamsAlertEpisodeActionType.ViewExecuteAlertEpisodeOnCallPolicy ||
            data.actionType ===
                MicrosoftTeamsAlertEpisodeActionType.SubmitExecuteAlertEpisodeOnCallPolicy ||
            data.actionType ===
                MicrosoftTeamsAlertEpisodeActionType.ViewChangeAlertEpisodeState ||
            data.actionType ===
                MicrosoftTeamsAlertEpisodeActionType.SubmitChangeAlertEpisodeState);
    }
    static async handleAlertEpisodeAction(data) {
        const { teamsRequest, action } = data;
        logger.debug("Handling Microsoft Teams alert episode action:", {
            projectId: teamsRequest.projectId.toString(),
            actionType: action.actionType,
        });
        logger.debug(action);
        try {
            switch (action.actionType) {
                case MicrosoftTeamsAlertEpisodeActionType.AckAlertEpisode:
                    await this.acknowledgeAlertEpisode({
                        teamsRequest,
                        action,
                    });
                    break;
                case MicrosoftTeamsAlertEpisodeActionType.ResolveAlertEpisode:
                    await this.resolveAlertEpisode({
                        teamsRequest,
                        action,
                    });
                    break;
                case MicrosoftTeamsAlertEpisodeActionType.ViewAlertEpisode:
                    // This is handled by opening the URL directly
                    break;
                default:
                    logger.debug("Unhandled alert episode action: " + action.actionType, {
                        projectId: teamsRequest.projectId.toString(),
                        actionType: action.actionType,
                    });
                    break;
            }
        }
        catch (error) {
            logger.error("Error handling Microsoft Teams alert episode action:", {
                projectId: teamsRequest.projectId.toString(),
                actionType: action.actionType,
            });
            logger.error(error);
        }
        Response.sendTextResponse(data.req, data.res, "");
    }
    static async acknowledgeAlertEpisode(data) {
        var _a;
        const episodeId = data.action.actionValue || "";
        if (!episodeId) {
            logger.error("No episode ID provided for acknowledge action", {
                projectId: data.teamsRequest.projectId.toString(),
            });
            return;
        }
        logger.debug("Acknowledging alert episode: " + episodeId, {
            projectId: data.teamsRequest.projectId.toString(),
            alertEpisodeId: episodeId,
        });
        try {
            const episode = await AlertEpisodeService.findOneBy({
                query: {
                    _id: episodeId,
                    projectId: data.teamsRequest.projectId,
                },
                select: {
                    _id: true,
                    projectId: true,
                    currentAlertState: {
                        _id: true,
                        name: true,
                        isAcknowledgedState: true,
                    },
                },
                props: {
                    isRoot: true,
                },
            });
            if (!episode) {
                logger.error("Alert episode not found: " + episodeId, {
                    projectId: data.teamsRequest.projectId.toString(),
                    alertEpisodeId: episodeId,
                });
                return;
            }
            if ((_a = episode.currentAlertState) === null || _a === void 0 ? void 0 : _a.isAcknowledgedState) {
                logger.debug("Alert episode is already acknowledged", {
                    projectId: data.teamsRequest.projectId.toString(),
                    alertEpisodeId: episodeId,
                });
                return;
            }
            const oneUptimeUserId = await MicrosoftTeamsAuthAction.getOneUptimeUserIdFromTeamsUserId({
                teamsUserId: data.teamsRequest.userId || "",
                projectId: data.teamsRequest.projectId,
            });
            await AlertEpisodeService.acknowledgeEpisode(new ObjectID(episodeId), oneUptimeUserId);
            logger.debug("Alert episode acknowledged successfully", {
                projectId: data.teamsRequest.projectId.toString(),
                alertEpisodeId: episodeId,
            });
        }
        catch (error) {
            logger.error("Error acknowledging alert episode:", {
                projectId: data.teamsRequest.projectId.toString(),
                alertEpisodeId: episodeId,
            });
            logger.error(error);
        }
    }
    static async resolveAlertEpisode(data) {
        var _a;
        const episodeId = data.action.actionValue || "";
        if (!episodeId) {
            logger.error("No episode ID provided for resolve action", {
                projectId: data.teamsRequest.projectId.toString(),
            });
            return;
        }
        logger.debug("Resolving alert episode: " + episodeId, {
            projectId: data.teamsRequest.projectId.toString(),
            alertEpisodeId: episodeId,
        });
        try {
            const episode = await AlertEpisodeService.findOneBy({
                query: {
                    _id: episodeId,
                    projectId: data.teamsRequest.projectId,
                },
                select: {
                    _id: true,
                    projectId: true,
                    currentAlertState: {
                        _id: true,
                        name: true,
                        isResolvedState: true,
                    },
                },
                props: {
                    isRoot: true,
                },
            });
            if (!episode) {
                logger.error("Alert episode not found: " + episodeId, {
                    projectId: data.teamsRequest.projectId.toString(),
                    alertEpisodeId: episodeId,
                });
                return;
            }
            if ((_a = episode.currentAlertState) === null || _a === void 0 ? void 0 : _a.isResolvedState) {
                logger.debug("Alert episode is already resolved", {
                    projectId: data.teamsRequest.projectId.toString(),
                    alertEpisodeId: episodeId,
                });
                return;
            }
            const oneUptimeUserId = await MicrosoftTeamsAuthAction.getOneUptimeUserIdFromTeamsUserId({
                teamsUserId: data.teamsRequest.userId || "",
                projectId: data.teamsRequest.projectId,
            });
            await AlertEpisodeService.resolveEpisode(new ObjectID(episodeId), oneUptimeUserId);
            logger.debug("Alert episode resolved successfully", {
                projectId: data.teamsRequest.projectId.toString(),
                alertEpisodeId: episodeId,
            });
        }
        catch (error) {
            logger.error("Error resolving alert episode:", {
                projectId: data.teamsRequest.projectId.toString(),
                alertEpisodeId: episodeId,
            });
            logger.error(error);
        }
    }
    static async handleBotAlertEpisodeAction(data) {
        var _a, _b;
        const { actionType, actionValue, value, projectId, oneUptimeUserId, turnContext, } = data;
        if (actionType === MicrosoftTeamsAlertEpisodeActionType.AckAlertEpisode) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to acknowledge: missing alert episode id.");
                return;
            }
            await AlertEpisodeService.acknowledgeEpisode(new ObjectID(actionValue), oneUptimeUserId);
            await turnContext.sendActivity("✅ Alert episode acknowledged.");
            return;
        }
        if (actionType === MicrosoftTeamsAlertEpisodeActionType.ResolveAlertEpisode) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to resolve: missing alert episode id.");
                return;
            }
            await AlertEpisodeService.resolveEpisode(new ObjectID(actionValue), oneUptimeUserId);
            await turnContext.sendActivity("✅ Alert episode resolved.");
            return;
        }
        if (actionType === MicrosoftTeamsAlertEpisodeActionType.ViewAlertEpisode) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to view alert episode: missing episode id.");
                return;
            }
            const episode = await AlertEpisodeService.findOneBy({
                query: {
                    _id: actionValue,
                    projectId: projectId,
                },
                select: {
                    _id: true,
                    title: true,
                    description: true,
                    currentAlertState: {
                        name: true,
                    },
                    alertSeverity: {
                        name: true,
                    },
                    createdAt: true,
                    alertCount: true,
                },
                props: {
                    isRoot: true,
                },
            });
            if (!episode) {
                await turnContext.sendActivity("Alert episode not found.");
                return;
            }
            const message = `**Alert Episode Details**\n\n**Title:** ${episode.title}\n**Description:** ${episode.description || "No description"}\n**State:** ${((_a = episode.currentAlertState) === null || _a === void 0 ? void 0 : _a.name) || "Unknown"}\n**Severity:** ${((_b = episode.alertSeverity) === null || _b === void 0 ? void 0 : _b.name) || "Unknown"}\n**Alert Count:** ${episode.alertCount || 0}\n**Created At:** ${episode.createdAt ? new Date(episode.createdAt).toLocaleString() : "Unknown"}`;
            await turnContext.sendActivity(message);
            return;
        }
        if (actionType ===
            MicrosoftTeamsAlertEpisodeActionType.ViewAddAlertEpisodeNote) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to add note: missing episode id.");
                return;
            }
            // Send the input card
            const card = this.buildAddAlertEpisodeNoteCard(actionValue);
            await turnContext.sendActivity({
                attachments: [
                    {
                        contentType: "application/vnd.microsoft.card.adaptive",
                        content: card,
                    },
                ],
            });
            return;
        }
        if (actionType === MicrosoftTeamsAlertEpisodeActionType.SubmitAlertEpisodeNote) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to add note: missing episode id.");
                return;
            }
            // Check if form data is provided
            const note = value["note"];
            if (note) {
                // Submit the note
                const episodeId = new ObjectID(actionValue);
                await AlertEpisodeInternalNoteService.addNote({
                    alertEpisodeId: episodeId,
                    note: note.toString(),
                    projectId: projectId,
                    userId: oneUptimeUserId,
                });
                await turnContext.sendActivity("✅ Note added successfully.");
                // Hide the form card by deleting it
                if (turnContext.activity.replyToId) {
                    await turnContext.deleteActivity(turnContext.activity.replyToId);
                }
                return;
            }
            await turnContext.sendActivity("Unable to add note: missing note data.");
            return;
        }
        if (actionType ===
            MicrosoftTeamsAlertEpisodeActionType.ViewExecuteAlertEpisodeOnCallPolicy) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to execute on-call policy: missing episode id.");
                return;
            }
            // Send the input card
            const card = await this.buildExecuteAlertEpisodeOnCallPolicyCard(actionValue, projectId);
            if (!card) {
                await turnContext.sendActivity("No on-call policies have been configured for this project yet. Please add an on-call policy in the OneUptime Dashboard under On-Call Duty > Policies to use this feature.");
                return;
            }
            await turnContext.sendActivity({
                attachments: [
                    {
                        contentType: "application/vnd.microsoft.card.adaptive",
                        content: card,
                    },
                ],
            });
            return;
        }
        if (actionType ===
            MicrosoftTeamsAlertEpisodeActionType.SubmitExecuteAlertEpisodeOnCallPolicy) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to execute on-call policy: missing episode id.");
                return;
            }
            // Check if form data is provided
            const onCallPolicyId = value["onCallPolicy"];
            if (onCallPolicyId) {
                // Execute the policy
                const episodeId = new ObjectID(actionValue);
                await OnCallDutyPolicyService.executePolicy(new ObjectID(onCallPolicyId.toString()), {
                    triggeredByAlertEpisodeId: episodeId,
                    userNotificationEventType: UserNotificationEventType.AlertEpisodeCreated,
                });
                await turnContext.sendActivity("✅ On-call policy executed successfully.");
                // Hide the form card by deleting it
                if (turnContext.activity.replyToId) {
                    await turnContext.deleteActivity(turnContext.activity.replyToId);
                }
                return;
            }
            await turnContext.sendActivity("Unable to execute on-call policy: missing policy id.");
            return;
        }
        if (actionType ===
            MicrosoftTeamsAlertEpisodeActionType.ViewChangeAlertEpisodeState) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to change episode state: missing episode id.");
                return;
            }
            // Send the input card
            const card = await this.buildChangeAlertEpisodeStateCard(actionValue, projectId);
            await turnContext.sendActivity({
                attachments: [
                    {
                        contentType: "application/vnd.microsoft.card.adaptive",
                        content: card,
                    },
                ],
            });
            return;
        }
        if (actionType ===
            MicrosoftTeamsAlertEpisodeActionType.SubmitChangeAlertEpisodeState) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to change episode state: missing episode id.");
                return;
            }
            // Check if form data is provided
            const alertStateId = value["alertState"];
            if (alertStateId) {
                // Update the state
                const episodeId = new ObjectID(actionValue);
                await AlertEpisodeService.changeEpisodeState({
                    projectId: projectId,
                    episodeId: episodeId,
                    alertStateId: new ObjectID(alertStateId.toString()),
                    notifyOwners: true,
                    rootCause: "State changed via Microsoft Teams.",
                    props: {
                        isRoot: true,
                    },
                });
                await turnContext.sendActivity("✅ Alert episode state changed successfully.");
                // Hide the form card by deleting it
                if (turnContext.activity.replyToId) {
                    await turnContext.deleteActivity(turnContext.activity.replyToId);
                }
                return;
            }
            await turnContext.sendActivity("Unable to change episode state: missing state id.");
            return;
        }
        // Default fallback for unimplemented actions
        await turnContext.sendActivity("Sorry, but the action " +
            actionType +
            " you requested is not implemented yet.");
    }
    static buildAddAlertEpisodeNoteCard(episodeId) {
        return {
            type: "AdaptiveCard",
            $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
            version: "1.5",
            body: [
                {
                    type: "TextBlock",
                    text: "Add Alert Episode Note",
                    size: "Large",
                    weight: "Bolder",
                },
                {
                    type: "Input.Text",
                    id: "note",
                    label: "Note",
                    isMultiline: true,
                    placeholder: "Please type in plain text or markdown.",
                },
            ],
            actions: [
                {
                    type: "Action.Submit",
                    title: "Submit",
                    data: {
                        action: MicrosoftTeamsAlertEpisodeActionType.SubmitAlertEpisodeNote,
                        actionValue: episodeId,
                    },
                },
            ],
        };
    }
    static async buildExecuteAlertEpisodeOnCallPolicyCard(episodeId, projectId) {
        const onCallPolicies = await OnCallDutyPolicyService.findBy({
            query: {
                projectId: projectId,
            },
            select: {
                name: true,
                _id: true,
            },
            props: {
                isRoot: true,
            },
            limit: 50,
            skip: 0,
        });
        const choices = onCallPolicies
            .map((policy) => {
            var _a;
            return {
                title: policy.name || "",
                value: ((_a = policy._id) === null || _a === void 0 ? void 0 : _a.toString()) || "",
            };
        })
            .filter((choice) => {
            return choice.title && choice.value;
        });
        if (choices.length === 0) {
            return null;
        }
        return {
            type: "AdaptiveCard",
            $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
            version: "1.5",
            body: [
                {
                    type: "TextBlock",
                    text: "Execute On-Call Policy",
                    size: "Large",
                    weight: "Bolder",
                },
                {
                    type: "Input.ChoiceSet",
                    id: "onCallPolicy",
                    label: "On-Call Policy",
                    style: "compact",
                    choices: choices,
                },
            ],
            actions: [
                {
                    type: "Action.Submit",
                    title: "Execute",
                    data: {
                        action: MicrosoftTeamsAlertEpisodeActionType.SubmitExecuteAlertEpisodeOnCallPolicy,
                        actionValue: episodeId,
                    },
                },
            ],
        };
    }
    static async buildChangeAlertEpisodeStateCard(episodeId, projectId) {
        const alertStates = await AlertStateService.getAllAlertStates({
            projectId: projectId,
            props: {
                isRoot: true,
            },
        });
        const choices = alertStates
            .map((state) => {
            var _a;
            return {
                title: state.name || "",
                value: ((_a = state._id) === null || _a === void 0 ? void 0 : _a.toString()) || "",
            };
        })
            .filter((choice) => {
            return choice.title && choice.value;
        });
        return {
            type: "AdaptiveCard",
            $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
            version: "1.5",
            body: [
                {
                    type: "TextBlock",
                    text: "Change Alert Episode State",
                    size: "Large",
                    weight: "Bolder",
                },
                {
                    type: "Input.ChoiceSet",
                    id: "alertState",
                    label: "Alert State",
                    style: "compact",
                    choices: choices,
                },
            ],
            actions: [
                {
                    type: "Action.Submit",
                    title: "Change",
                    data: {
                        action: MicrosoftTeamsAlertEpisodeActionType.SubmitChangeAlertEpisodeState,
                        actionValue: episodeId,
                    },
                },
            ],
        };
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Boolean)
], MicrosoftTeamsAlertEpisodeActions, "isAlertEpisodeAction", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MicrosoftTeamsAlertEpisodeActions, "handleAlertEpisodeAction", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MicrosoftTeamsAlertEpisodeActions, "acknowledgeAlertEpisode", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MicrosoftTeamsAlertEpisodeActions, "resolveAlertEpisode", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MicrosoftTeamsAlertEpisodeActions, "handleBotAlertEpisodeAction", null);
//# sourceMappingURL=AlertEpisode.js.map