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 DatabaseService from "./DatabaseService";
import Model from "../../Models/DatabaseModels/OnCallDutyPolicyExecutionLogTimeline";
import IncidentFeedService from "./IncidentFeedService";
import { IncidentFeedEventType } from "../../Models/DatabaseModels/IncidentFeed";
import OnCallDutyExecutionLogTimelineStatus from "../../Types/OnCallDutyPolicy/OnCalDutyExecutionLogTimelineStatus";
import { Blue500, Green500, Red500, Yellow500 } from "../../Types/BrandColors";
import logger from "../Utils/Logger";
import { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
import AlertFeedService from "./AlertFeedService";
import { AlertFeedEventType } from "../../Models/DatabaseModels/AlertFeed";
import AlertEpisodeFeedService from "./AlertEpisodeFeedService";
import { AlertEpisodeFeedEventType } from "../../Models/DatabaseModels/AlertEpisodeFeed";
import IncidentEpisodeFeedService from "./IncidentEpisodeFeedService";
import { IncidentEpisodeFeedEventType } from "../../Models/DatabaseModels/IncidentEpisodeFeed";
import OnCallDutyPolicyService from "./OnCallDutyPolicyService";
import AlertService from "./AlertService";
import AlertEpisodeService from "./AlertEpisodeService";
import IncidentEpisodeService from "./IncidentEpisodeService";
import IncidentService from "./IncidentService";
import UserService from "./UserService";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    getColorBasedOnStatus(status) {
        switch (status) {
            case OnCallDutyExecutionLogTimelineStatus.Started:
                return Blue500;
            case OnCallDutyExecutionLogTimelineStatus.Executing:
                return Yellow500;
            case OnCallDutyExecutionLogTimelineStatus.Error:
                return Red500;
            case OnCallDutyExecutionLogTimelineStatus.NotificationSent:
                return Green500;
            case OnCallDutyExecutionLogTimelineStatus.Skipped:
                return Red500;
            case OnCallDutyExecutionLogTimelineStatus.SuccessfullyAcknowledged:
                return Green500;
            default:
                return Blue500;
        }
    }
    getEmojiBasedOnStatus(status) {
        switch (status) {
            case OnCallDutyExecutionLogTimelineStatus.Started:
                return "🚀";
            case OnCallDutyExecutionLogTimelineStatus.Executing:
                return "🔄";
            case OnCallDutyExecutionLogTimelineStatus.Error:
                return "❌";
            case OnCallDutyExecutionLogTimelineStatus.NotificationSent:
                return "📧";
            case OnCallDutyExecutionLogTimelineStatus.Skipped:
                return "🚫";
            case OnCallDutyExecutionLogTimelineStatus.SuccessfullyAcknowledged:
                return "✅";
            default:
                return "🚀";
        }
    }
    async addToIncidentOrAlertFeed(data) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
        logger.debug("OnCallDutyPolicyExecutionLogTimelineService.addToIncidentFeed", {
            onCallDutyPolicyExecutionLogTimelineId: (_a = data.onCallDutyPolicyExecutionLogTimelineId) === null || _a === void 0 ? void 0 : _a.toString(),
        });
        const onCallDutyPolicyExecutionLogTimeline = await this.findOneById({
            id: data.onCallDutyPolicyExecutionLogTimelineId,
            select: {
                _id: true,
                onCallDutyPolicyId: true,
                triggeredByIncidentId: true,
                triggeredByAlertId: true,
                triggeredByAlertEpisodeId: true,
                projectId: true,
                status: true,
                statusMessage: true,
                alertSentToUserId: true,
                onCallDutyPolicy: {
                    name: true,
                    _id: true,
                },
                alertSentToUser: {
                    name: true,
                    email: true,
                },
                onCallDutyPolicyEscalationRule: {
                    name: true,
                    _id: true,
                },
                onCallDutySchedule: {
                    name: true,
                    _id: true,
                },
                isAcknowledged: true,
                acknowledgedAt: true,
                userBelongsToTeam: {
                    name: true,
                    _id: true,
                },
                overridedByUser: {
                    name: true,
                    _id: true,
                },
            },
            props: {
                isRoot: true,
            },
        });
        logger.debug("OnCallDutyPolicyExecutionLogTimeline: ", {
            projectId: (_b = onCallDutyPolicyExecutionLogTimeline === null || onCallDutyPolicyExecutionLogTimeline === void 0 ? void 0 : onCallDutyPolicyExecutionLogTimeline.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
        });
        logger.debug(onCallDutyPolicyExecutionLogTimeline, {
            projectId: (_c = onCallDutyPolicyExecutionLogTimeline === null || onCallDutyPolicyExecutionLogTimeline === void 0 ? void 0 : onCallDutyPolicyExecutionLogTimeline.projectId) === null || _c === void 0 ? void 0 : _c.toString(),
        });
        if (!onCallDutyPolicyExecutionLogTimeline) {
            return;
        }
        if (!onCallDutyPolicyExecutionLogTimeline.triggeredByIncidentId &&
            !onCallDutyPolicyExecutionLogTimeline.triggeredByAlertId &&
            !onCallDutyPolicyExecutionLogTimeline.triggeredByAlertEpisodeId &&
            !onCallDutyPolicyExecutionLogTimeline.triggeredByIncidentEpisodeId) {
            return;
        }
        if (onCallDutyPolicyExecutionLogTimeline.onCallDutyPolicy &&
            onCallDutyPolicyExecutionLogTimeline.onCallDutyPolicy.id) {
            const status = onCallDutyPolicyExecutionLogTimeline.status;
            logger.debug("Status: " + status, {
                projectId: (_d = onCallDutyPolicyExecutionLogTimeline === null || onCallDutyPolicyExecutionLogTimeline === void 0 ? void 0 : onCallDutyPolicyExecutionLogTimeline.projectId) === null || _d === void 0 ? void 0 : _d.toString(),
            });
            if (status &&
                (status === OnCallDutyExecutionLogTimelineStatus.Skipped ||
                    status === OnCallDutyExecutionLogTimelineStatus.Error ||
                    status ===
                        OnCallDutyExecutionLogTimelineStatus.SuccessfullyAcknowledged ||
                    status === OnCallDutyExecutionLogTimelineStatus.NotificationSent)) {
                const displayColor = status
                    ? this.getColorBasedOnStatus(status)
                    : Blue500;
                let incidentOrAlertLink = "";
                if (onCallDutyPolicyExecutionLogTimeline.triggeredByIncidentId) {
                    const projectId = onCallDutyPolicyExecutionLogTimeline.projectId;
                    const incidentId = onCallDutyPolicyExecutionLogTimeline.triggeredByIncidentId;
                    const incidentNumberResult = await IncidentService.getIncidentNumber({
                        incidentId: incidentId,
                    });
                    const incidentNumberDisplay = incidentNumberResult.numberWithPrefix ||
                        "#" + incidentNumberResult.number;
                    incidentOrAlertLink = `[Incident ${incidentNumberDisplay}](${(await IncidentService.getIncidentLinkInDashboard(projectId, incidentId)).toString()})`;
                }
                if (onCallDutyPolicyExecutionLogTimeline.triggeredByAlertId) {
                    const alertNumberResult = await AlertService.getAlertNumber({
                        alertId: onCallDutyPolicyExecutionLogTimeline.triggeredByAlertId,
                    });
                    incidentOrAlertLink = `[Alert ${alertNumberResult.numberWithPrefix || "#" + alertNumberResult.number}](${(await AlertService.getAlertLinkInDashboard(onCallDutyPolicyExecutionLogTimeline.projectId, onCallDutyPolicyExecutionLogTimeline.triggeredByAlertId)).toString()})`;
                }
                if (onCallDutyPolicyExecutionLogTimeline.triggeredByAlertEpisodeId) {
                    const alertEpisodeNumberResult = await AlertEpisodeService.getEpisodeNumber({
                        episodeId: onCallDutyPolicyExecutionLogTimeline.triggeredByAlertEpisodeId,
                    });
                    incidentOrAlertLink = `[Alert Episode ${alertEpisodeNumberResult.numberWithPrefix || "#" + alertEpisodeNumberResult.number}](${(await AlertEpisodeService.getEpisodeLinkInDashboard(onCallDutyPolicyExecutionLogTimeline.projectId, onCallDutyPolicyExecutionLogTimeline.triggeredByAlertEpisodeId)).toString()})`;
                }
                if (onCallDutyPolicyExecutionLogTimeline.triggeredByIncidentEpisodeId) {
                    const incidentEpisodeNumberResult = await IncidentEpisodeService.getEpisodeNumber({
                        episodeId: onCallDutyPolicyExecutionLogTimeline.triggeredByIncidentEpisodeId,
                    });
                    incidentOrAlertLink = `[Incident Episode ${incidentEpisodeNumberResult.numberWithPrefix || "#" + incidentEpisodeNumberResult.number}](${(await IncidentEpisodeService.getEpisodeLinkInDashboard(onCallDutyPolicyExecutionLogTimeline.projectId, onCallDutyPolicyExecutionLogTimeline.triggeredByIncidentEpisodeId)).toString()})`;
                }
                let feedInfoInMarkdown = `**${this.getEmojiBasedOnStatus(status)} ${incidentOrAlertLink} On-Call Alert ${status} to ${await UserService.getUserMarkdownString({
                    userId: onCallDutyPolicyExecutionLogTimeline.alertSentToUserId,
                    projectId: onCallDutyPolicyExecutionLogTimeline.projectId,
                })}**

The on-call policy **[${onCallDutyPolicyExecutionLogTimeline.onCallDutyPolicy.name}](${(await OnCallDutyPolicyService.getOnCallDutyPolicyLinkInDashboard(onCallDutyPolicyExecutionLogTimeline.projectId, onCallDutyPolicyExecutionLogTimeline.onCallDutyPolicy.id)).toString()})** has been triggered. The escalation rule **${(_e = onCallDutyPolicyExecutionLogTimeline.onCallDutyPolicyEscalationRule) === null || _e === void 0 ? void 0 : _e.name}** ${((_f = onCallDutyPolicyExecutionLogTimeline.onCallDutySchedule) === null || _f === void 0 ? void 0 : _f.name) ? String(" and schedule **" + ((_g = onCallDutyPolicyExecutionLogTimeline.onCallDutySchedule) === null || _g === void 0 ? void 0 : _g.name) + "**") : ""} were applied. ${await UserService.getUserMarkdownString({
                    userId: onCallDutyPolicyExecutionLogTimeline.alertSentToUserId,
                    projectId: onCallDutyPolicyExecutionLogTimeline.projectId,
                })} was alerted. The status of this alert is **${status}** with the message: \`${onCallDutyPolicyExecutionLogTimeline.statusMessage}\`. ${((_h = onCallDutyPolicyExecutionLogTimeline.userBelongsToTeam) === null || _h === void 0 ? void 0 : _h.name) ? "The alert was sent because the user belogs to the team **" + ((_j = onCallDutyPolicyExecutionLogTimeline.userBelongsToTeam) === null || _j === void 0 ? void 0 : _j.name) + "** " : ""} ${onCallDutyPolicyExecutionLogTimeline.isAcknowledged ? "The alert was acknowledged at **" + onCallDutyPolicyExecutionLogTimeline.acknowledgedAt + "** " : ""}`;
                if (onCallDutyPolicyExecutionLogTimeline.overridedByUser) {
                    feedInfoInMarkdown += `The alert was supposed to be sent to **${await UserService.getUserMarkdownString({
                        userId: onCallDutyPolicyExecutionLogTimeline.overridedByUser.id,
                        projectId: onCallDutyPolicyExecutionLogTimeline.projectId,
                    })}** but was routed to **${await UserService.getUserMarkdownString({
                        userId: onCallDutyPolicyExecutionLogTimeline.alertSentToUserId,
                        projectId: onCallDutyPolicyExecutionLogTimeline.projectId,
                    })}** instead, because of an override rule.`;
                }
                logger.debug("Feed Info in Markdown: " + feedInfoInMarkdown, {
                    projectId: (_k = onCallDutyPolicyExecutionLogTimeline === null || onCallDutyPolicyExecutionLogTimeline === void 0 ? void 0 : onCallDutyPolicyExecutionLogTimeline.projectId) === null || _k === void 0 ? void 0 : _k.toString(),
                });
                if (onCallDutyPolicyExecutionLogTimeline.triggeredByIncidentId) {
                    await IncidentFeedService.createIncidentFeedItem({
                        incidentId: onCallDutyPolicyExecutionLogTimeline.triggeredByIncidentId,
                        projectId: onCallDutyPolicyExecutionLogTimeline.projectId,
                        incidentFeedEventType: IncidentFeedEventType.OnCallPolicy,
                        displayColor: displayColor,
                        feedInfoInMarkdown: feedInfoInMarkdown,
                        workspaceNotification: {
                            sendWorkspaceNotification: true,
                        },
                    });
                }
                if (onCallDutyPolicyExecutionLogTimeline.triggeredByAlertId) {
                    await AlertFeedService.createAlertFeedItem({
                        alertId: onCallDutyPolicyExecutionLogTimeline.triggeredByAlertId,
                        projectId: onCallDutyPolicyExecutionLogTimeline.projectId,
                        alertFeedEventType: AlertFeedEventType.OnCallPolicy,
                        displayColor: displayColor,
                        feedInfoInMarkdown: feedInfoInMarkdown,
                    });
                }
                if (onCallDutyPolicyExecutionLogTimeline.triggeredByAlertEpisodeId) {
                    await AlertEpisodeFeedService.createAlertEpisodeFeedItem({
                        alertEpisodeId: onCallDutyPolicyExecutionLogTimeline.triggeredByAlertEpisodeId,
                        projectId: onCallDutyPolicyExecutionLogTimeline.projectId,
                        alertEpisodeFeedEventType: AlertEpisodeFeedEventType.OnCallNotification,
                        displayColor: displayColor,
                        feedInfoInMarkdown: feedInfoInMarkdown,
                    });
                }
                if (onCallDutyPolicyExecutionLogTimeline.triggeredByIncidentEpisodeId) {
                    await IncidentEpisodeFeedService.createIncidentEpisodeFeedItem({
                        incidentEpisodeId: onCallDutyPolicyExecutionLogTimeline.triggeredByIncidentEpisodeId,
                        projectId: onCallDutyPolicyExecutionLogTimeline.projectId,
                        incidentEpisodeFeedEventType: IncidentEpisodeFeedEventType.OnCallNotification,
                        displayColor: displayColor,
                        feedInfoInMarkdown: feedInfoInMarkdown,
                    });
                }
                logger.debug("Incident Feed created", {
                    projectId: (_l = onCallDutyPolicyExecutionLogTimeline === null || onCallDutyPolicyExecutionLogTimeline === void 0 ? void 0 : onCallDutyPolicyExecutionLogTimeline.projectId) === null || _l === void 0 ? void 0 : _l.toString(),
                });
            }
        }
    }
    async onCreateSuccess(_onCreate, createdItem) {
        var _a, _b;
        logger.debug("OnCallDutyPolicyExecutionLogTimelineService.onCreateSuccess", { projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString() });
        logger.debug(createdItem, {
            projectId: (_b = createdItem.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
        });
        await this.addToIncidentOrAlertFeed({
            onCallDutyPolicyExecutionLogTimelineId: createdItem.id,
        });
        return createdItem;
    }
    async onUpdateSuccess(onUpdate, _updatedItemIds) {
        if (onUpdate.updateBy.query) {
            const updatedItems = await this.findBy({
                query: onUpdate.updateBy.query,
                props: {
                    isRoot: true,
                },
                select: {
                    _id: true,
                },
                limit: LIMIT_PER_PROJECT,
                skip: 0,
            });
            for (const updatedItem of updatedItems) {
                await this.addToIncidentOrAlertFeed({
                    onCallDutyPolicyExecutionLogTimelineId: updatedItem.id,
                });
            }
        }
        return onUpdate;
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "addToIncidentOrAlertFeed", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Model]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onCreateSuccess", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Array]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onUpdateSuccess", null);
export default new Service();
//# sourceMappingURL=OnCallDutyPolicyExecutionLogTimelineService.js.map