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 { MicrosoftTeamsIncidentActionType } from "./ActionTypes";
import logger from "../../../Logger";
import ObjectID from "../../../../../Types/ObjectID";
import IncidentService from "../../../../Services/IncidentService";
import Incident from "../../../../../Models/DatabaseModels/Incident";
import CaptureSpan from "../../../Telemetry/CaptureSpan";
import IncidentPublicNoteService from "../../../../Services/IncidentPublicNoteService";
import IncidentInternalNoteService from "../../../../Services/IncidentInternalNoteService";
import OnCallDutyPolicyService from "../../../../Services/OnCallDutyPolicyService";
import IncidentStateService from "../../../../Services/IncidentStateService";
import UserNotificationEventType from "../../../../../Types/UserNotification/UserNotificationEventType";
import OnCallDutyPolicy from "../../../../../Models/DatabaseModels/OnCallDutyPolicy";
import IncidentSeverityService from "../../../../Services/IncidentSeverityService";
import MonitorService from "../../../../Services/MonitorService";
import Monitor from "../../../../../Models/DatabaseModels/Monitor";
import MonitorStatusService from "../../../../Services/MonitorStatusService";
import LabelService from "../../../../Services/LabelService";
import Label from "../../../../../Models/DatabaseModels/Label";
import SortOrder from "../../../../../Types/BaseDatabase/SortOrder";
import { LIMIT_PER_PROJECT } from "../../../../../Types/Database/LimitMax";
import BadDataException from "../../../../../Types/Exception/BadDataException";
export default class MicrosoftTeamsIncidentActions {
    static isIncidentAction(data) {
        // Check if the action is related to incidents
        return (data.actionType === MicrosoftTeamsIncidentActionType.AckIncident ||
            data.actionType === MicrosoftTeamsIncidentActionType.ResolveIncident ||
            data.actionType === MicrosoftTeamsIncidentActionType.ViewIncident ||
            data.actionType === MicrosoftTeamsIncidentActionType.IncidentCreated ||
            data.actionType ===
                MicrosoftTeamsIncidentActionType.IncidentStateChanged ||
            data.actionType ===
                MicrosoftTeamsIncidentActionType.ViewAddIncidentNote ||
            data.actionType === MicrosoftTeamsIncidentActionType.SubmitIncidentNote ||
            data.actionType ===
                MicrosoftTeamsIncidentActionType.ExecuteIncidentOnCallPolicy ||
            data.actionType ===
                MicrosoftTeamsIncidentActionType.ViewExecuteIncidentOnCallPolicy ||
            data.actionType ===
                MicrosoftTeamsIncidentActionType.SubmitExecuteIncidentOnCallPolicy ||
            data.actionType ===
                MicrosoftTeamsIncidentActionType.ViewChangeIncidentState ||
            data.actionType ===
                MicrosoftTeamsIncidentActionType.SubmitChangeIncidentState ||
            data.actionType === MicrosoftTeamsIncidentActionType.NewIncident ||
            data.actionType === MicrosoftTeamsIncidentActionType.SubmitNewIncident);
    }
    static async handleIncidentAction(data) {
        const { teamsRequest, action } = data;
        logger.debug("Handling Microsoft Teams incident action:", {
            projectId: teamsRequest.projectId.toString(),
            actionType: action.actionType,
        });
        logger.debug(action);
        try {
            switch (action.actionType) {
                case MicrosoftTeamsIncidentActionType.AckIncident:
                    await this.acknowledgeIncident({
                        teamsRequest,
                        action,
                    });
                    break;
                case MicrosoftTeamsIncidentActionType.ResolveIncident:
                    await this.resolveIncident({
                        teamsRequest,
                        action,
                    });
                    break;
                case MicrosoftTeamsIncidentActionType.ViewIncident:
                    // This is handled by opening the URL directly
                    break;
                case MicrosoftTeamsIncidentActionType.NewIncident:
                    return await this.showNewIncidentCard(data);
                case MicrosoftTeamsIncidentActionType.SubmitNewIncident:
                    /*
                     * This is handled by handleBotIncidentAction through bot framework
                     * Don't process it here to avoid duplicate messages
                     */
                    break;
                default:
                    logger.debug("Unhandled incident action: " + action.actionType, {
                        projectId: teamsRequest.projectId.toString(),
                        actionType: action.actionType,
                    });
                    break;
            }
        }
        catch (error) {
            logger.error("Error handling Microsoft Teams incident action:", {
                projectId: teamsRequest.projectId.toString(),
                actionType: action.actionType,
            });
            logger.error(error);
        }
        // Send empty response to Teams
        Response.sendTextResponse(data.req, data.res, "");
    }
    static async acknowledgeIncident(data) {
        var _a;
        const incidentId = data.action.actionValue || "";
        if (!incidentId) {
            logger.error("No incident ID provided for acknowledge action", {
                projectId: data.teamsRequest.projectId.toString(),
            });
            return;
        }
        logger.debug("Acknowledging incident: " + incidentId, {
            projectId: data.teamsRequest.projectId.toString(),
            incidentId: incidentId,
        });
        try {
            // Get the incident
            const incident = await IncidentService.findOneBy({
                query: {
                    _id: incidentId,
                    projectId: data.teamsRequest.projectId,
                },
                select: {
                    _id: true,
                    projectId: true,
                    currentIncidentState: {
                        _id: true,
                        name: true,
                        isAcknowledgedState: true,
                    },
                },
                props: {
                    isRoot: true,
                },
            });
            if (!incident) {
                logger.error("Incident not found: " + incidentId, {
                    projectId: data.teamsRequest.projectId.toString(),
                    incidentId: incidentId,
                });
                return;
            }
            // Check if already acknowledged
            if ((_a = incident.currentIncidentState) === null || _a === void 0 ? void 0 : _a.isAcknowledgedState) {
                logger.debug("Incident is already acknowledged", {
                    projectId: data.teamsRequest.projectId.toString(),
                    incidentId: incidentId,
                });
                return;
            }
            // Acknowledge the incident
            const oneUptimeUserId = await MicrosoftTeamsAuthAction.getOneUptimeUserIdFromTeamsUserId({
                teamsUserId: data.teamsRequest.userId || "",
                projectId: data.teamsRequest.projectId,
            });
            await IncidentService.acknowledgeIncident(new ObjectID(incidentId), oneUptimeUserId);
            logger.debug("Incident acknowledged successfully", {
                projectId: data.teamsRequest.projectId.toString(),
                incidentId: incidentId,
            });
        }
        catch (error) {
            logger.error("Error acknowledging incident:", {
                projectId: data.teamsRequest.projectId.toString(),
                incidentId: incidentId,
            });
            logger.error(error);
        }
    }
    static async resolveIncident(data) {
        var _a;
        const incidentId = data.action.actionValue || "";
        if (!incidentId) {
            logger.error("No incident ID provided for resolve action", {
                projectId: data.teamsRequest.projectId.toString(),
            });
            return;
        }
        logger.debug("Resolving incident: " + incidentId, {
            projectId: data.teamsRequest.projectId.toString(),
            incidentId: incidentId,
        });
        try {
            // Get the incident
            const incident = await IncidentService.findOneBy({
                query: {
                    _id: incidentId,
                    projectId: data.teamsRequest.projectId,
                },
                select: {
                    _id: true,
                    projectId: true,
                    currentIncidentState: {
                        _id: true,
                        name: true,
                        isResolvedState: true,
                    },
                },
                props: {
                    isRoot: true,
                },
            });
            if (!incident) {
                logger.error("Incident not found: " + incidentId, {
                    projectId: data.teamsRequest.projectId.toString(),
                    incidentId: incidentId,
                });
                return;
            }
            // Check if already resolved
            if ((_a = incident.currentIncidentState) === null || _a === void 0 ? void 0 : _a.isResolvedState) {
                logger.debug("Incident is already resolved", {
                    projectId: data.teamsRequest.projectId.toString(),
                    incidentId: incidentId,
                });
                return;
            }
            // Resolve the incident
            const oneUptimeUserId = await MicrosoftTeamsAuthAction.getOneUptimeUserIdFromTeamsUserId({
                teamsUserId: data.teamsRequest.userId || "",
                projectId: data.teamsRequest.projectId,
            });
            await IncidentService.resolveIncident(new ObjectID(incidentId), oneUptimeUserId);
            logger.debug("Incident resolved successfully", {
                projectId: data.teamsRequest.projectId.toString(),
                incidentId: incidentId,
            });
        }
        catch (error) {
            logger.error("Error resolving incident:", {
                projectId: data.teamsRequest.projectId.toString(),
                incidentId: incidentId,
            });
            logger.error(error);
        }
    }
    static async handleBotIncidentAction(data) {
        var _a, _b, _c, _d;
        const { actionType, actionValue, value, projectId, oneUptimeUserId, turnContext, } = data;
        if (actionType === MicrosoftTeamsIncidentActionType.AckIncident) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to acknowledge: missing incident id.");
                return;
            }
            await IncidentService.acknowledgeIncident(new ObjectID(actionValue), oneUptimeUserId);
            await turnContext.sendActivity("✅ Incident acknowledged.");
            return;
        }
        if (actionType === MicrosoftTeamsIncidentActionType.ResolveIncident) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to resolve: missing incident id.");
                return;
            }
            await IncidentService.resolveIncident(new ObjectID(actionValue), oneUptimeUserId);
            await turnContext.sendActivity("✅ Incident resolved.");
            return;
        }
        if (actionType === MicrosoftTeamsIncidentActionType.ViewIncident) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to view incident: missing incident id.");
                return;
            }
            const incident = await IncidentService.findOneBy({
                query: {
                    _id: actionValue,
                    projectId: projectId,
                },
                select: {
                    _id: true,
                    title: true,
                    description: true,
                    currentIncidentState: {
                        name: true,
                    },
                    incidentSeverity: {
                        name: true,
                    },
                    createdAt: true,
                    declaredAt: true,
                },
                props: {
                    isRoot: true,
                },
            });
            if (!incident) {
                await turnContext.sendActivity("Incident not found.");
                return;
            }
            const declaredAt = incident.declaredAt || incident.createdAt || undefined;
            const message = `**Incident Details**\n\n**Title:** ${incident.title}\n**Description:** ${incident.description || "No description"}\n**State:** ${((_a = incident.currentIncidentState) === null || _a === void 0 ? void 0 : _a.name) || "Unknown"}\n**Severity:** ${((_b = incident.incidentSeverity) === null || _b === void 0 ? void 0 : _b.name) || "Unknown"}\n**Declared At:** ${declaredAt ? new Date(declaredAt).toLocaleString() : "Unknown"}`;
            await turnContext.sendActivity(message);
            return;
        }
        if (actionType === MicrosoftTeamsIncidentActionType.ViewAddIncidentNote) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to add note: missing incident id.");
                return;
            }
            // Send the input card
            const card = this.buildAddIncidentNoteCard(actionValue);
            await turnContext.sendActivity({
                attachments: [
                    {
                        contentType: "application/vnd.microsoft.card.adaptive",
                        content: card,
                    },
                ],
            });
            return;
        }
        if (actionType === MicrosoftTeamsIncidentActionType.SubmitIncidentNote) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to add note: missing incident id.");
                return;
            }
            // Check if form data is provided
            const noteType = value["noteType"];
            const note = value["note"];
            if (noteType && note) {
                // Submit the note
                const incidentId = new ObjectID(actionValue);
                if (noteType === "public") {
                    await IncidentPublicNoteService.addNote({
                        incidentId: incidentId,
                        note: note.toString(),
                        projectId: projectId,
                        userId: oneUptimeUserId,
                    });
                }
                else if (noteType === "private") {
                    await IncidentInternalNoteService.addNote({
                        incidentId: incidentId,
                        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 ===
            MicrosoftTeamsIncidentActionType.ViewExecuteIncidentOnCallPolicy) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to execute on-call policy: missing incident id.");
                return;
            }
            // Send the input card
            const card = await this.buildExecuteOnCallPolicyCard(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 ===
            MicrosoftTeamsIncidentActionType.SubmitExecuteIncidentOnCallPolicy) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to execute on-call policy: missing incident id.");
                return;
            }
            // Check if form data is provided
            const onCallPolicyId = value["onCallPolicy"];
            if (onCallPolicyId) {
                // Execute the policy
                const incidentId = new ObjectID(actionValue);
                await OnCallDutyPolicyService.executePolicy(new ObjectID(onCallPolicyId.toString()), {
                    triggeredByIncidentId: incidentId,
                    userNotificationEventType: UserNotificationEventType.IncidentCreated,
                });
                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 === MicrosoftTeamsIncidentActionType.ViewChangeIncidentState) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to change incident state: missing incident id.");
                return;
            }
            // Send the input card
            const card = await this.buildChangeIncidentStateCard(actionValue, projectId);
            await turnContext.sendActivity({
                attachments: [
                    {
                        contentType: "application/vnd.microsoft.card.adaptive",
                        content: card,
                    },
                ],
            });
            return;
        }
        if (actionType === MicrosoftTeamsIncidentActionType.SubmitChangeIncidentState) {
            if (!actionValue) {
                await turnContext.sendActivity("Unable to change incident state: missing incident id.");
                return;
            }
            // Check if form data is provided
            const incidentStateId = value["incidentState"];
            if (incidentStateId) {
                // Update the state
                const incidentId = new ObjectID(actionValue);
                await IncidentService.updateOneById({
                    id: incidentId,
                    data: {
                        currentIncidentStateId: new ObjectID(incidentStateId.toString()),
                    },
                    props: {
                        isRoot: true,
                    },
                });
                await turnContext.sendActivity("✅ Incident 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 incident state: missing state id.");
            return;
        }
        if (actionType === MicrosoftTeamsIncidentActionType.SubmitNewIncident) {
            // Handle new incident submission
            const title = value["incidentTitle"] || "";
            const description = value["incidentDescription"] || "";
            const severityId = value["incidentSeverity"] || "";
            const monitorIds = value["incidentMonitors"] || "";
            const monitorStatusId = value["monitorStatus"] || "";
            const labelIds = value["labels"] || "";
            const onCallPolicyIds = value["onCallDutyPolicies"] || "";
            if (!title || !description || !severityId) {
                await turnContext.sendActivity("Unable to create incident: missing required fields (title, description, or severity).");
                return;
            }
            try {
                // Create the incident
                const incident = new Incident();
                incident.title = title;
                incident.description = description;
                incident.projectId = projectId;
                incident.createdByUserId = oneUptimeUserId;
                incident.incidentSeverityId = new ObjectID(severityId);
                incident.rootCause = `Incident created via Microsoft Teams`;
                // Parse monitors
                if (monitorIds) {
                    const monitorIdArray = monitorIds
                        .split(",")
                        .map((id) => {
                        return id.trim();
                    })
                        .filter((id) => {
                        return id;
                    });
                    if (monitorIdArray.length > 0) {
                        incident.monitors = monitorIdArray.map((id) => {
                            const monitor = new Monitor();
                            monitor.id = new ObjectID(id);
                            return monitor;
                        });
                    }
                }
                // Parse labels
                if (labelIds) {
                    const labelIdArray = labelIds
                        .split(",")
                        .map((id) => {
                        return id.trim();
                    })
                        .filter((id) => {
                        return id;
                    });
                    if (labelIdArray.length > 0) {
                        incident.labels = labelIdArray.map((id) => {
                            const label = new Label();
                            label.id = new ObjectID(id);
                            return label;
                        });
                    }
                }
                // Parse on-call policies
                if (onCallPolicyIds) {
                    const policyIdArray = onCallPolicyIds
                        .split(",")
                        .map((id) => {
                        return id.trim();
                    })
                        .filter((id) => {
                        return id;
                    });
                    if (policyIdArray.length > 0) {
                        incident.onCallDutyPolicies = policyIdArray.map((id) => {
                            const policy = new OnCallDutyPolicy();
                            policy.id = new ObjectID(id);
                            return policy;
                        });
                    }
                }
                // Save the incident
                const createdIncident = await IncidentService.create({
                    data: incident,
                    props: {
                        isRoot: true,
                    },
                });
                logger.debug("Incident created successfully: " + ((_c = createdIncident.id) === null || _c === void 0 ? void 0 : _c.toString()), {
                    projectId: projectId.toString(),
                    incidentId: (_d = createdIncident.id) === null || _d === void 0 ? void 0 : _d.toString(),
                });
                // Update monitor status if specified
                if (monitorStatusId && monitorIds) {
                    const monitorIdArray = monitorIds
                        .split(",")
                        .map((id) => {
                        return id.trim();
                    })
                        .filter((id) => {
                        return id;
                    });
                    for (const monitorId of monitorIdArray) {
                        await MonitorService.updateOneById({
                            id: new ObjectID(monitorId),
                            data: {
                                currentMonitorStatusId: new ObjectID(monitorStatusId),
                            },
                            props: {
                                isRoot: true,
                            },
                        });
                    }
                }
                // Hide the form card by deleting it first
                if (turnContext.activity.replyToId) {
                    await turnContext.deleteActivity(turnContext.activity.replyToId);
                }
                // Get the incident link
                const incidentLink = await IncidentService.getIncidentLinkInDashboard(projectId, createdIncident.id);
                // Send confirmation message as a new message in the thread
                await turnContext.sendActivity(`✅ Incident created successfully!\n\nView incident: ${incidentLink.toString()}`);
                return;
            }
            catch (error) {
                logger.error("Error creating incident from Microsoft Teams:", {
                    projectId: projectId.toString(),
                });
                logger.error(error);
                await turnContext.sendActivity("❌ Failed to create incident. Please try again.");
                return;
            }
        }
        // Default fallback for unimplemented actions
        await turnContext.sendActivity("Sorry, but the action " +
            actionType +
            " you requested is not implemented yet.");
    }
    static buildAddIncidentNoteCard(incidentId) {
        return {
            type: "AdaptiveCard",
            $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
            version: "1.5",
            body: [
                {
                    type: "TextBlock",
                    text: "Add Incident Note",
                    size: "Large",
                    weight: "Bolder",
                },
                {
                    type: "Input.ChoiceSet",
                    id: "noteType",
                    label: "Note Type",
                    style: "compact",
                    value: "public",
                    choices: [
                        {
                            title: "Public Note (Will be posted on Status Page)",
                            value: "public",
                        },
                        {
                            title: "Private Note (Only visible to team members)",
                            value: "private",
                        },
                    ],
                },
                {
                    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: MicrosoftTeamsIncidentActionType.SubmitIncidentNote,
                        actionValue: incidentId,
                    },
                },
            ],
        };
    }
    static async buildExecuteOnCallPolicyCard(incidentId, 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: MicrosoftTeamsIncidentActionType.SubmitExecuteIncidentOnCallPolicy,
                        actionValue: incidentId,
                    },
                },
            ],
        };
    }
    static async buildChangeIncidentStateCard(incidentId, projectId) {
        const incidentStates = await IncidentStateService.getAllIncidentStates({
            projectId: projectId,
            props: {
                isRoot: true,
            },
        });
        const choices = incidentStates
            .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 Incident State",
                    size: "Large",
                    weight: "Bolder",
                },
                {
                    type: "Input.ChoiceSet",
                    id: "incidentState",
                    label: "Incident State",
                    style: "compact",
                    choices: choices,
                },
            ],
            actions: [
                {
                    type: "Action.Submit",
                    title: "Change",
                    data: {
                        action: MicrosoftTeamsIncidentActionType.SubmitChangeIncidentState,
                        actionValue: incidentId,
                    },
                },
            ],
        };
    }
    static async showNewIncidentCard(data) {
        var _a;
        const { teamsRequest, req, res } = data;
        logger.debug("Showing new incident card for Microsoft Teams", {
            projectId: (_a = teamsRequest.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
        });
        // Send empty response first
        Response.sendTextResponse(req, res, "");
        if (!teamsRequest.projectId) {
            logger.error("Project ID not found in Teams request");
            return;
        }
        // Build the adaptive card with form fields
        const card = await this.buildNewIncidentCard(teamsRequest.projectId);
        /*
         * Send card as a message (note: in real Teams bot, this would be sent via TurnContext)
         * For now, we'll just log it. The actual sending will be done through the bot framework
         */
        logger.debug("New incident card built:", {
            projectId: teamsRequest.projectId.toString(),
        });
        logger.debug(JSON.stringify(card, null, 2));
    }
    static async submitNewIncident(data) {
        var _a, _b;
        const { teamsRequest, req, res } = data;
        const { userId, projectId } = teamsRequest;
        logger.debug("Submitting new incident from Microsoft Teams", {
            projectId: projectId === null || projectId === void 0 ? void 0 : projectId.toString(),
        });
        if (!projectId) {
            return Response.sendErrorResponse(req, res, new BadDataException("Invalid Project ID"));
        }
        if (!userId) {
            return Response.sendErrorResponse(req, res, new BadDataException("Invalid User ID"));
        }
        // Send early response
        Response.sendTextResponse(req, res, "");
        // Extract form data from the payload
        const payload = teamsRequest.payload || {};
        const value = payload["value"] || {};
        const title = value["incidentTitle"] || "";
        const description = value["incidentDescription"] || "";
        const severityId = value["incidentSeverity"] || "";
        const monitorIds = value["incidentMonitors"] || "";
        const monitorStatusId = value["monitorStatus"] || "";
        const labelIds = value["labels"] || "";
        const onCallPolicyIds = value["onCallDutyPolicies"] || "";
        if (!title || !description || !severityId) {
            logger.error("Missing required fields for incident creation", {
                projectId: projectId.toString(),
            });
            return;
        }
        try {
            // Get OneUptime user ID
            const oneUptimeUserId = await MicrosoftTeamsAuthAction.getOneUptimeUserIdFromTeamsUserId({
                teamsUserId: userId,
                projectId: projectId,
            });
            // Create the incident
            const incident = new Incident();
            incident.title = title;
            incident.description = description;
            incident.projectId = projectId;
            incident.createdByUserId = oneUptimeUserId;
            incident.incidentSeverityId = new ObjectID(severityId);
            incident.rootCause = `Incident created via Microsoft Teams`;
            // Parse monitors
            if (monitorIds) {
                const monitorIdArray = monitorIds
                    .split(",")
                    .map((id) => {
                    return id.trim();
                })
                    .filter((id) => {
                    return id;
                });
                if (monitorIdArray.length > 0) {
                    incident.monitors = monitorIdArray.map((id) => {
                        const monitor = new Monitor();
                        monitor.id = new ObjectID(id);
                        return monitor;
                    });
                }
            }
            // Parse labels
            if (labelIds) {
                const labelIdArray = labelIds
                    .split(",")
                    .map((id) => {
                    return id.trim();
                })
                    .filter((id) => {
                    return id;
                });
                if (labelIdArray.length > 0) {
                    incident.labels = labelIdArray.map((id) => {
                        const label = new Label();
                        label.id = new ObjectID(id);
                        return label;
                    });
                }
            }
            // Parse on-call policies
            if (onCallPolicyIds) {
                const policyIdArray = onCallPolicyIds
                    .split(",")
                    .map((id) => {
                    return id.trim();
                })
                    .filter((id) => {
                    return id;
                });
                if (policyIdArray.length > 0) {
                    incident.onCallDutyPolicies = policyIdArray.map((id) => {
                        const policy = new OnCallDutyPolicy();
                        policy.id = new ObjectID(id);
                        return policy;
                    });
                }
            }
            // Save the incident
            const createdIncident = await IncidentService.create({
                data: incident,
                props: {
                    isRoot: true,
                },
            });
            logger.debug("Incident created successfully: " + ((_a = createdIncident.id) === null || _a === void 0 ? void 0 : _a.toString()), {
                projectId: projectId.toString(),
                incidentId: (_b = createdIncident.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
            // Update monitor status if specified
            if (monitorStatusId && monitorIds) {
                const monitorIdArray = monitorIds
                    .split(",")
                    .map((id) => {
                    return id.trim();
                })
                    .filter((id) => {
                    return id;
                });
                for (const monitorId of monitorIdArray) {
                    await MonitorService.updateOneById({
                        id: new ObjectID(monitorId),
                        data: {
                            currentMonitorStatusId: new ObjectID(monitorStatusId),
                        },
                        props: {
                            isRoot: true,
                        },
                    });
                }
            }
            logger.debug("New incident created from Microsoft Teams successfully", {
                projectId: projectId.toString(),
            });
        }
        catch (error) {
            logger.error("Error creating incident from Microsoft Teams:", {
                projectId: projectId.toString(),
            });
            logger.error(error);
        }
    }
    static async buildNewIncidentCard(projectId) {
        // Fetch severities
        const severities = await IncidentSeverityService.findBy({
            query: {
                projectId: projectId,
            },
            sort: {
                order: SortOrder.Ascending,
            },
            skip: 0,
            limit: LIMIT_PER_PROJECT,
            select: {
                name: true,
            },
            props: {
                isRoot: true,
            },
        });
        const severityChoices = severities.map((severity) => {
            var _a;
            return {
                title: severity.name || "",
                value: ((_a = severity._id) === null || _a === void 0 ? void 0 : _a.toString()) || "",
            };
        });
        // Fetch monitors
        const monitors = await MonitorService.findBy({
            query: {
                projectId: projectId,
            },
            select: {
                name: true,
            },
            props: {
                isRoot: true,
            },
            limit: LIMIT_PER_PROJECT,
            skip: 0,
        });
        const monitorChoices = monitors
            .map((monitor) => {
            var _a;
            return {
                title: monitor.name || "",
                value: ((_a = monitor._id) === null || _a === void 0 ? void 0 : _a.toString()) || "",
            };
        })
            .filter((choice) => {
            return choice.title && choice.value;
        });
        // Fetch monitor statuses
        const monitorStatuses = await MonitorStatusService.findBy({
            query: {
                projectId: projectId,
            },
            select: {
                name: true,
            },
            props: {
                isRoot: true,
            },
            sort: {
                priority: SortOrder.Ascending,
            },
            limit: LIMIT_PER_PROJECT,
            skip: 0,
        });
        const monitorStatusChoices = monitorStatuses
            .map((status) => {
            var _a;
            return {
                title: status.name || "",
                value: ((_a = status._id) === null || _a === void 0 ? void 0 : _a.toString()) || "",
            };
        })
            .filter((choice) => {
            return choice.title && choice.value;
        });
        // Fetch labels
        const labels = await LabelService.findBy({
            query: {
                projectId: projectId,
            },
            select: {
                name: true,
            },
            props: {
                isRoot: true,
            },
            limit: LIMIT_PER_PROJECT,
            skip: 0,
        });
        const labelChoices = labels
            .map((label) => {
            var _a;
            return {
                title: label.name || "",
                value: ((_a = label._id) === null || _a === void 0 ? void 0 : _a.toString()) || "",
            };
        })
            .filter((choice) => {
            return choice.title && choice.value;
        });
        // Fetch on-call policies
        const onCallPolicies = await OnCallDutyPolicyService.findBy({
            query: {
                projectId: projectId,
            },
            select: {
                name: true,
            },
            props: {
                isRoot: true,
            },
            limit: LIMIT_PER_PROJECT,
            skip: 0,
        });
        const onCallPolicyChoices = 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;
        });
        // Build the card
        const bodyElements = [
            {
                type: "TextBlock",
                text: "Create New Incident",
                size: "Large",
                weight: "Bolder",
            },
            {
                type: "Input.Text",
                id: "incidentTitle",
                label: "Incident Title",
                placeholder: "Enter incident title",
                isRequired: true,
            },
            {
                type: "Input.Text",
                id: "incidentDescription",
                label: "Incident Description",
                placeholder: "Enter incident description",
                isMultiline: true,
                isRequired: true,
            },
        ];
        // Add severity dropdown if we have severities
        if (severityChoices.length > 0) {
            bodyElements.push({
                type: "Input.ChoiceSet",
                id: "incidentSeverity",
                label: "Incident Severity",
                style: "compact",
                isRequired: true,
                choices: severityChoices,
            });
        }
        // Add monitor multi-select if we have monitors
        if (monitorChoices.length > 0) {
            bodyElements.push({
                type: "Input.ChoiceSet",
                id: "incidentMonitors",
                label: "Affected Monitors (Optional)",
                style: "compact",
                isMultiSelect: true,
                choices: monitorChoices,
            });
        }
        // Add monitor status dropdown if we have statuses and monitors
        if (monitorStatusChoices.length > 0 && monitorChoices.length > 0) {
            bodyElements.push({
                type: "Input.ChoiceSet",
                id: "monitorStatus",
                label: "Change Monitor Status To (Optional)",
                style: "compact",
                choices: monitorStatusChoices,
            });
        }
        // Add on-call policy multi-select if we have policies
        if (onCallPolicyChoices.length > 0) {
            bodyElements.push({
                type: "Input.ChoiceSet",
                id: "onCallDutyPolicies",
                label: "Execute On-Call Policies (Optional)",
                style: "compact",
                isMultiSelect: true,
                choices: onCallPolicyChoices,
            });
        }
        // Add labels multi-select if we have labels
        if (labelChoices.length > 0) {
            bodyElements.push({
                type: "Input.ChoiceSet",
                id: "labels",
                label: "Labels (Optional)",
                style: "compact",
                isMultiSelect: true,
                choices: labelChoices,
            });
        }
        return {
            type: "AdaptiveCard",
            $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
            version: "1.5",
            body: bodyElements,
            actions: [
                {
                    type: "Action.Submit",
                    title: "Create Incident",
                    data: {
                        action: MicrosoftTeamsIncidentActionType.SubmitNewIncident,
                    },
                },
            ],
        };
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Boolean)
], MicrosoftTeamsIncidentActions, "isIncidentAction", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MicrosoftTeamsIncidentActions, "handleIncidentAction", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MicrosoftTeamsIncidentActions, "acknowledgeIncident", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MicrosoftTeamsIncidentActions, "resolveIncident", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MicrosoftTeamsIncidentActions, "handleBotIncidentAction", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MicrosoftTeamsIncidentActions, "showNewIncidentCard", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MicrosoftTeamsIncidentActions, "submitNewIncident", null);
//# sourceMappingURL=Incident.js.map