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 DatabaseConfig from "../DatabaseConfig";
import { AllowedActiveMonitorCountInFreePlan, IsBillingEnabled, } from "../EnvironmentConfig";
import { ActiveMonitoringMeteredPlan } from "../Types/Billing/MeteredPlan/AllMeteredPlans";
import QueryHelper from "../Types/Database/QueryHelper";
import DatabaseService from "./DatabaseService";
import MonitorLabelRuleEngineService from "./MonitorLabelRuleEngineService";
import MonitorOwnerRuleEngineService from "./MonitorOwnerRuleEngineService";
import MonitorOwnerTeamService from "./MonitorOwnerTeamService";
import MonitorOwnerUserService from "./MonitorOwnerUserService";
import MonitorProbeService from "./MonitorProbeService";
import MonitorStatusService from "./MonitorStatusService";
import MonitorStatusTimelineService from "./MonitorStatusTimelineService";
import ProbeService from "./ProbeService";
import ProjectService from "./ProjectService";
import TeamMemberService from "./TeamMemberService";
import URL from "../../Types/API/URL";
import SortOrder from "../../Types/BaseDatabase/SortOrder";
import { PlanType } from "../../Types/Billing/SubscriptionPlan";
import LIMIT_MAX, { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
import BadDataException from "../../Types/Exception/BadDataException";
import MonitorType, { MonitorTypeHelper, } from "../../Types/Monitor/MonitorType";
import MonitorSteps from "../../Types/Monitor/MonitorSteps";
import MonitorStep from "../../Types/Monitor/MonitorStep";
import ObjectID from "../../Types/ObjectID";
import Typeof from "../../Types/Typeof";
import Model from "../../Models/DatabaseModels/Monitor";
import MonitorOwnerTeam from "../../Models/DatabaseModels/MonitorOwnerTeam";
import MonitorOwnerUser from "../../Models/DatabaseModels/MonitorOwnerUser";
import MonitorProbe from "../../Models/DatabaseModels/MonitorProbe";
import MonitorStatusTimeline from "../../Models/DatabaseModels/MonitorStatusTimeline";
import { ProbeConnectionStatus, } from "../../Models/DatabaseModels/Probe";
import EmailTemplateType from "../../Types/Email/EmailTemplateType";
import Markdown, { MarkdownContentType } from "../Types/Markdown";
import UserNotificationSettingService from "./UserNotificationSettingService";
import NotificationSettingEventType from "../../Types/NotificationSetting/NotificationSettingEventType";
import StatusPageResourceService from "./StatusPageResourceService";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import WorkspaceNotificationRuleService from "./WorkspaceNotificationRuleService";
import MonitorWorkspaceMessages from "../Utils/Workspace/WorkspaceMessages/Monitor";
import MonitorFeedService from "./MonitorFeedService";
import { MonitorFeedEventType } from "../../Models/DatabaseModels/MonitorFeed";
import { Gray500, Green500 } from "../../Types/BrandColors";
import LabelService from "./LabelService";
import logger from "../Utils/Logger";
import PushNotificationUtil from "../Utils/PushNotificationUtil";
import ExceptionMessages from "../../Types/Exception/ExceptionMessages";
import { createWhatsAppMessageFromTemplate } from "../Utils/WhatsAppTemplateUtil";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    getMonitorDestinationInfo(monitor) {
        var _a, _b, _c, _d, _e, _f, _g;
        let monitorDestination = "";
        let requestType = "";
        const monitorType = monitor.monitorType;
        if (monitor.monitorSteps) {
            const monitorSteps = monitor.monitorSteps;
            const stepsArray = ((_a = monitorSteps.data) === null || _a === void 0 ? void 0 : _a.monitorStepsInstanceArray) || [];
            if (stepsArray.length > 0) {
                const firstStep = stepsArray[0];
                // Get monitor destination
                if ((_b = firstStep === null || firstStep === void 0 ? void 0 : firstStep.data) === null || _b === void 0 ? void 0 : _b.monitorDestination) {
                    monitorDestination =
                        firstStep.data.monitorDestination.toString() || "";
                }
                // Get request type for API monitors
                if (monitorType === MonitorType.API && ((_c = firstStep === null || firstStep === void 0 ? void 0 : firstStep.data) === null || _c === void 0 ? void 0 : _c.requestType)) {
                    requestType = firstStep.data.requestType;
                }
                // For port monitors, append port to destination
                if (monitorType === MonitorType.Port &&
                    ((_d = firstStep === null || firstStep === void 0 ? void 0 : firstStep.data) === null || _d === void 0 ? void 0 : _d.monitorDestinationPort)) {
                    const port = firstStep.data.monitorDestinationPort.toString();
                    if (monitorDestination && port) {
                        monitorDestination = `${monitorDestination}:${port}`;
                    }
                }
                // For SNMP monitors, use the hostname from snmpMonitor config
                if (monitorType === MonitorType.SNMP && ((_e = firstStep === null || firstStep === void 0 ? void 0 : firstStep.data) === null || _e === void 0 ? void 0 : _e.snmpMonitor)) {
                    monitorDestination = firstStep.data.snmpMonitor.hostname || "";
                    const port = firstStep.data.snmpMonitor.port || 161;
                    if (monitorDestination && port) {
                        monitorDestination = `${monitorDestination}:${port}`;
                    }
                }
                // For DNS monitors, use the queryName from dnsMonitor config
                if (monitorType === MonitorType.DNS && ((_f = firstStep === null || firstStep === void 0 ? void 0 : firstStep.data) === null || _f === void 0 ? void 0 : _f.dnsMonitor)) {
                    monitorDestination = firstStep.data.dnsMonitor.queryName || "";
                    if (firstStep.data.dnsMonitor.hostname) {
                        monitorDestination = `${monitorDestination} @${firstStep.data.dnsMonitor.hostname}`;
                    }
                }
                // For External Status Page monitors, use the statusPageUrl
                if (monitorType === MonitorType.ExternalStatusPage &&
                    ((_g = firstStep === null || firstStep === void 0 ? void 0 : firstStep.data) === null || _g === void 0 ? void 0 : _g.externalStatusPageMonitor)) {
                    monitorDestination =
                        firstStep.data.externalStatusPageMonitor.statusPageUrl || "";
                }
            }
        }
        return {
            monitorDestination,
            requestType,
            monitorType: monitorType || "",
        };
    }
    extractMonitorStepIds(monitorSteps) {
        var _a, _b;
        const stepIds = [];
        let stepsArray = [];
        if (monitorSteps instanceof MonitorSteps) {
            stepsArray = ((_a = monitorSteps.data) === null || _a === void 0 ? void 0 : _a.monitorStepsInstanceArray) || [];
        }
        else if (monitorSteps && typeof monitorSteps === "object") {
            const value = monitorSteps["value"];
            const rawArray = value
                ? value["monitorStepsInstanceArray"]
                : monitorSteps["monitorStepsInstanceArray"];
            if (Array.isArray(rawArray)) {
                stepsArray = rawArray;
            }
        }
        for (const step of stepsArray) {
            let stepId;
            if (step instanceof MonitorStep) {
                stepId = (_b = step.data) === null || _b === void 0 ? void 0 : _b.id;
            }
            else if (step && typeof step === "object") {
                const wrappedValue = step["value"];
                stepId = ((wrappedValue === null || wrappedValue === void 0 ? void 0 : wrappedValue["id"]) || step["id"]);
            }
            if (stepId) {
                stepIds.push(stepId.toString());
            }
        }
        return stepIds;
    }
    async refreshMonitorCurrentStatus(monitorId) {
        var _a;
        const monitor = await this.findOneById({
            id: monitorId,
            select: {
                _id: true,
                currentMonitorStatusId: true,
            },
            props: {
                isRoot: true,
                ignoreHooks: true,
            },
        });
        const lastMonitorStatus = await MonitorStatusTimelineService.findOneBy({
            query: {
                monitorId: monitorId,
                endsAt: QueryHelper.isNull(),
            },
            select: {
                _id: true,
                monitorStatusId: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!lastMonitorStatus) {
            return;
        }
        if (!lastMonitorStatus.monitorStatusId) {
            return;
        }
        if (!monitor) {
            return;
        }
        if (((_a = monitor.currentMonitorStatusId) === null || _a === void 0 ? void 0 : _a.toString()) !==
            lastMonitorStatus.monitorStatusId.toString()) {
            await this.updateOneById({
                id: monitor.id,
                data: {
                    currentMonitorStatusId: lastMonitorStatus.monitorStatusId,
                },
                props: {
                    isRoot: true,
                },
            });
        }
    }
    async onBeforeDelete(deleteBy) {
        var _a, _b, _c;
        const monitorsPendingDeletion = await this.findBy({
            query: deleteBy.query,
            limit: LIMIT_MAX,
            skip: 0,
            select: {
                _id: true,
                projectId: true,
            },
            props: deleteBy.props,
        });
        for (const monitor of monitorsPendingDeletion) {
            if (!monitor.id) {
                continue;
            }
            // delete all the status page resources for this monitor.
            await StatusPageResourceService.deleteBy({
                query: {
                    monitorId: monitor.id,
                },
                limit: LIMIT_MAX,
                skip: 0,
                props: {
                    isRoot: true,
                },
            });
            const projectId = monitor.projectId;
            if (!projectId) {
                continue;
            }
            try {
                await WorkspaceNotificationRuleService.archiveWorkspaceChannels({
                    projectId: projectId,
                    notificationFor: {
                        monitorId: monitor.id,
                    },
                    sendMessageBeforeArchiving: {
                        _type: "WorkspacePayloadMarkdown",
                        text: `🗑️ This monitor is deleted. The channel is being archived.`,
                    },
                });
            }
            catch (error) {
                logger.error(`Error while archiving workspace channels for monitor ${(_a = monitor.id) === null || _a === void 0 ? void 0 : _a.toString()}: ${error}`, {
                    projectId: (_b = monitor.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
                    monitorId: (_c = monitor.id) === null || _c === void 0 ? void 0 : _c.toString(),
                });
            }
        }
        return {
            deleteBy,
            carryForward: {
                monitors: monitorsPendingDeletion,
            },
        };
    }
    async onDeleteSuccess(onDelete, _itemIdsBeforeDelete) {
        var _a;
        /*
         * The monitor has already been deleted from the database at this point.
         * Any failure in the post-delete side effects below (e.g. billing
         * reporting) must NOT propagate up to the caller as a 500 — otherwise the
         * client sees "500 Internal Server Error" even though the delete actually
         * succeeded. Log and swallow instead.
         *
         * Note: we intentionally do NOT delete Metric rows for this monitor here.
         * The Metric table has a ClickHouse TTL on retentionDate (set at ingest
         * from GlobalConfig.monitorMetricRetentionInDays) that auto-drops rows.
         * A synchronous ALTER TABLE … DELETE on every monitor deletion is both
         * redundant and expensive.
         */
        if (onDelete.deleteBy.props.tenantId && IsBillingEnabled) {
            try {
                await ActiveMonitoringMeteredPlan.reportQuantityToBillingProvider(onDelete.deleteBy.props.tenantId);
            }
            catch (error) {
                logger.error(`Error while reporting active monitor quantity to billing provider for project ${(_a = onDelete.deleteBy.props.tenantId) === null || _a === void 0 ? void 0 : _a.toString()}: ${error}`);
            }
        }
        return onDelete;
    }
    async onUpdateSuccess(onUpdate, updatedItemIds) {
        if (onUpdate.updateBy.data.currentMonitorStatusId &&
            onUpdate.updateBy.props.tenantId) {
            await this.changeMonitorStatus(onUpdate.updateBy.props.tenantId, updatedItemIds, onUpdate.updateBy.data.currentMonitorStatusId, true, // notifyOwners = true
            "This status was changed when the monitor was updated.", undefined, {
                isRoot: true,
            });
        }
        if (updatedItemIds.length > 0) {
            for (const monitorId of updatedItemIds) {
                const monitor = await this.findOneById({
                    id: monitorId,
                    select: {
                        projectId: true,
                        name: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                const projectId = monitor.projectId;
                const monitorName = monitor.name;
                let shouldAddMonitorFeed = false;
                let feedInfoInMarkdown = `Monitor **[${monitorName}](${(await this.getMonitorLinkInDashboard(projectId, monitorId)).toString()}) was updated.**`;
                const createdByUserId = onUpdate.updateBy.props.userId;
                if (onUpdate.updateBy.data.monitoringInterval) {
                    await MonitorProbeService.updateNextPingAtForMonitor({
                        monitorId: monitorId,
                    });
                }
                if (onUpdate.updateBy.data.monitorSteps) {
                    const validMonitorStepIds = this.extractMonitorStepIds(onUpdate.updateBy.data.monitorSteps);
                    await MonitorProbeService.pruneStaleLastMonitoringLogEntries({
                        monitorId: monitorId,
                        validMonitorStepIds: validMonitorStepIds,
                    });
                }
                if (onUpdate.updateBy.data.name) {
                    // add monitor feed.
                    feedInfoInMarkdown += `\n\n**Name**: 
    ${onUpdate.updateBy.data.name || "No name provided."}
    `;
                    shouldAddMonitorFeed = true;
                }
                if (onUpdate.updateBy.data.description) {
                    // add monitor feed.
                    feedInfoInMarkdown += `\n\n**Monitor Description**: 
              ${onUpdate.updateBy.data.description || "No description provided."}
              `;
                    shouldAddMonitorFeed = true;
                }
                if (onUpdate.updateBy.data.labels &&
                    onUpdate.updateBy.data.labels.length > 0 &&
                    Array.isArray(onUpdate.updateBy.data.labels)) {
                    const labelIds = onUpdate.updateBy.data.labels
                        .map((label) => {
                        var _a;
                        if (label._id) {
                            return new ObjectID((_a = label._id) === null || _a === void 0 ? void 0 : _a.toString());
                        }
                        return null;
                    })
                        .filter((labelId) => {
                        return labelId !== null;
                    });
                    const labels = await LabelService.findBy({
                        query: {
                            _id: QueryHelper.any(labelIds),
                        },
                        select: {
                            name: true,
                        },
                        limit: LIMIT_PER_PROJECT,
                        skip: 0,
                        props: {
                            isRoot: true,
                        },
                    });
                    if (labels.length > 0) {
                        feedInfoInMarkdown += `\n\n**🏷️ Labels**:
    
    ${labels
                            .map((label) => {
                            return `- ${label.name}`;
                        })
                            .join("\n")}
    `;
                        shouldAddMonitorFeed = true;
                    }
                }
                if (shouldAddMonitorFeed) {
                    await MonitorFeedService.createMonitorFeedItem({
                        monitorId: monitorId,
                        projectId: onUpdate.updateBy.props.tenantId,
                        monitorFeedEventType: MonitorFeedEventType.MonitorUpdated,
                        displayColor: Gray500,
                        feedInfoInMarkdown: feedInfoInMarkdown,
                        userId: createdByUserId || undefined,
                        workspaceNotification: {
                            sendWorkspaceNotification: true,
                        },
                    });
                }
            }
        }
        return onUpdate;
    }
    getEnabledMonitorQuery() {
        return {
            disableActiveMonitoring: false, // do not fetch if disabled is true.
            disableActiveMonitoringBecauseOfManualIncident: false,
            disableActiveMonitoringBecauseOfScheduledMaintenanceEvent: false,
        };
    }
    async onBeforeCreate(createBy) {
        if (!createBy.data.monitorType) {
            throw new BadDataException("Monitor type required to create monitor.");
        }
        if (!Object.values(MonitorType).includes(createBy.data.monitorType)) {
            throw new BadDataException(`Invalid monitor type "${createBy.data.monitorType}". Valid monitor types are ${Object.values(MonitorType).join(", ")}.`);
        }
        if (IsBillingEnabled && createBy.props.tenantId) {
            const currentPlan = await ProjectService.getCurrentPlan(createBy.props.tenantId);
            if (currentPlan.isSubscriptionUnpaid) {
                throw new BadDataException("Your subscription is unpaid. Please update your payment method and pay all the outstanding invoices to add more monitors.");
            }
            if (currentPlan.plan === PlanType.Free &&
                createBy.data.monitorType !== MonitorType.Manual) {
                const monitorCount = await this.countBy({
                    query: {
                        projectId: createBy.props.tenantId,
                        monitorType: QueryHelper.any(MonitorTypeHelper.getActiveMonitorTypes()),
                    },
                    props: {
                        isRoot: true,
                    },
                });
                if (monitorCount.toNumber() >= AllowedActiveMonitorCountInFreePlan) {
                    throw new BadDataException(`You have reached the maximum allowed monitor limit for the free plan. Please upgrade your plan to add more monitors.`);
                }
            }
        }
        if (createBy.data.monitorType === MonitorType.Server) {
            createBy.data.serverMonitorSecretKey = ObjectID.generate();
        }
        if (createBy.data.monitorType === MonitorType.IncomingRequest) {
            createBy.data.incomingRequestSecretKey = ObjectID.generate();
        }
        if (createBy.data.monitorType === MonitorType.IncomingEmail) {
            createBy.data.incomingEmailSecretKey = ObjectID.generate();
        }
        if (!createBy.props.tenantId) {
            throw new BadDataException("ProjectId required to create monitor.");
        }
        const monitorStatus = await MonitorStatusService.findOneBy({
            query: {
                projectId: createBy.props.tenantId,
                isOperationalState: true,
            },
            select: {
                _id: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!monitorStatus || !monitorStatus.id) {
            throw new BadDataException("Operational status not found for this project. Please add an operational status");
        }
        createBy.data.currentMonitorStatusId = monitorStatus.id;
        return { createBy, carryForward: null };
    }
    async onCreateSuccess(onCreate, createdItem) {
        var _a, _b, _c, _d;
        if (!createdItem.projectId) {
            throw new BadDataException("projectId is required");
        }
        if (!createdItem.id) {
            throw new BadDataException("id is required");
        }
        if (!createdItem.currentMonitorStatusId) {
            throw new BadDataException("currentMonitorStatusId is required");
        }
        const monitor = await this.findOneById({
            id: createdItem.id,
            select: {
                projectId: true,
                name: true,
                description: true,
                monitorType: true,
                currentMonitorStatus: {
                    name: true,
                },
                labels: {
                    name: true,
                },
            },
            props: {
                isRoot: true,
            },
        });
        const createdByUserId = createdItem.createdByUserId || ((_a = createdItem.createdByUser) === null || _a === void 0 ? void 0 : _a.id);
        let feedInfoInMarkdown = `#### 🌎 Monitor Created: 
          
**${((_b = createdItem.name) === null || _b === void 0 ? void 0 : _b.trim()) || "No name provided."}**:

${((_c = createdItem.description) === null || _c === void 0 ? void 0 : _c.trim()) || "No description provided."}
    
`;
        if ((_d = monitor === null || monitor === void 0 ? void 0 : monitor.currentMonitorStatus) === null || _d === void 0 ? void 0 : _d.name) {
            feedInfoInMarkdown += `➡️ **Monitor Status**: ${monitor.currentMonitorStatus.name} \n\n`;
        }
        if (monitor === null || monitor === void 0 ? void 0 : monitor.monitorType) {
            feedInfoInMarkdown += `⚙️ **Monitor Type**: ${monitor.monitorType} \n\n`;
        }
        if ((monitor === null || monitor === void 0 ? void 0 : monitor.labels) && monitor.labels.length > 0) {
            feedInfoInMarkdown += `🏷️ **Labels**:\n`;
            for (const label of monitor.labels) {
                feedInfoInMarkdown += `- ${label.name}\n`;
            }
            feedInfoInMarkdown += `\n\n`;
        }
        // Execute operations sequentially with error handling (workspace first)
        Promise.resolve()
            .then(async () => {
            var _a, _b;
            try {
                return await this.handleWorkspaceOperationsAsync({
                    projectId: createdItem.projectId,
                    monitorId: createdItem.id,
                    monitorName: createdItem.name,
                    feedInfoInMarkdown,
                    createdByUserId,
                });
            }
            catch (error) {
                logger.error("Workspace operations failed in MonitorService.onCreateSuccess", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    monitorId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
                logger.error(error);
                return Promise.resolve();
            }
        })
            .then(async () => {
            var _a, _b;
            try {
                return await this.changeMonitorStatus(createdItem.projectId, [createdItem.id], createdItem.currentMonitorStatusId, false, // notifyOwners = false
                "This status was created when the monitor was created.", undefined, onCreate.createBy.props);
            }
            catch (error) {
                logger.error("Change monitor status failed in MonitorService.onCreateSuccess", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    monitorId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
                logger.error(error);
                return Promise.resolve();
            }
        })
            .then(async () => {
            var _a, _b;
            try {
                if (createdItem.monitorType &&
                    MonitorTypeHelper.isProbableMonitor(createdItem.monitorType)) {
                    return await this.addDefaultProbesToMonitor(createdItem.projectId, createdItem.id);
                }
                return Promise.resolve();
            }
            catch (error) {
                logger.error("Add default probes failed in MonitorService.onCreateSuccess", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    monitorId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
                logger.error(error);
                return Promise.resolve();
            }
        })
            .then(async () => {
            var _a, _b;
            try {
                if (IsBillingEnabled) {
                    return await ActiveMonitoringMeteredPlan.reportQuantityToBillingProvider(createdItem.projectId);
                }
                return Promise.resolve();
            }
            catch (error) {
                logger.error("Billing operations failed in MonitorService.onCreateSuccess", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    monitorId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
                logger.error(error);
                return Promise.resolve();
            }
        })
            .then(async () => {
            var _a, _b;
            try {
                if (onCreate.createBy.miscDataProps &&
                    (onCreate.createBy.miscDataProps["ownerTeams"] ||
                        onCreate.createBy.miscDataProps["ownerUsers"])) {
                    return await this.addOwners(createdItem.projectId, createdItem.id, onCreate.createBy.miscDataProps["ownerUsers"] || [], onCreate.createBy.miscDataProps["ownerTeams"] || [], false, onCreate.createBy.props);
                }
                return Promise.resolve();
            }
            catch (error) {
                logger.error("Add owners failed in MonitorService.onCreateSuccess", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    monitorId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
                logger.error(error);
                return Promise.resolve();
            }
        })
            .then(async () => {
            var _a, _b;
            /*
             * Apply label rules first so rule-added labels are persisted before
             * owner rules run. Owner rules re-fetch labels from the DB, so this
             * lets owner rules key on rule-added labels.
             */
            try {
                await MonitorLabelRuleEngineService.applyRulesToMonitor(createdItem);
            }
            catch (error) {
                logger.error("Apply monitor label rules failed in MonitorService.onCreateSuccess", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    monitorId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
                logger.error(error);
                return Promise.resolve();
            }
            return Promise.resolve();
        })
            .then(async () => {
            var _a, _b;
            try {
                await MonitorOwnerRuleEngineService.applyRulesToMonitor(createdItem);
            }
            catch (error) {
                logger.error("Apply monitor owner rules failed in MonitorService.onCreateSuccess", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    monitorId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
                logger.error(error);
                return Promise.resolve();
            }
            return Promise.resolve();
        })
            .then(async () => {
            var _a, _b;
            try {
                return await this.refreshMonitorProbeStatus(createdItem.id);
            }
            catch (error) {
                logger.error("Refresh probe status failed in MonitorService.onCreateSuccess", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    monitorId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
                logger.error(error);
                return Promise.resolve();
            }
        })
            .catch((error) => {
            var _a, _b;
            logger.error(`Critical error in MonitorService sequential operations: ${error}`, {
                projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                monitorId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        });
        return createdItem;
    }
    async handleWorkspaceOperationsAsync(data) {
        var _a;
        // send message to workspaces - slack, teams, etc.
        const workspaceResult = await MonitorWorkspaceMessages.createChannelsAndInviteUsersToChannels({
            projectId: data.projectId,
            monitorId: data.monitorId,
            monitorName: data.monitorName,
        });
        if (workspaceResult && ((_a = workspaceResult.channelsCreated) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            // update monitor with these channels.
            await this.updateOneById({
                id: data.monitorId,
                data: {
                    postUpdatesToWorkspaceChannels: workspaceResult.channelsCreated || [],
                },
                props: {
                    isRoot: true,
                },
            });
        }
        const monitorCreateMessageBlocks = await MonitorWorkspaceMessages.getMonitorCreateMessageBlocks({
            monitorId: data.monitorId,
            projectId: data.projectId,
        });
        await MonitorFeedService.createMonitorFeedItem({
            monitorId: data.monitorId,
            projectId: data.projectId,
            monitorFeedEventType: MonitorFeedEventType.MonitorCreated,
            displayColor: Green500,
            feedInfoInMarkdown: data.feedInfoInMarkdown,
            userId: data.createdByUserId || undefined,
            workspaceNotification: {
                appendMessageBlocks: monitorCreateMessageBlocks,
                sendWorkspaceNotification: true,
            },
        });
    }
    async getMonitorLinkInDashboard(projectId, monitorId) {
        const dashboardUrl = await DatabaseConfig.getDashboardUrl();
        return URL.fromString(dashboardUrl.toString()).addRoute(`/${projectId.toString()}/monitors/${monitorId.toString()}`);
    }
    async findOwners(monitorId) {
        if (!monitorId) {
            throw new BadDataException("monitorId is required");
        }
        const ownerUsers = await MonitorOwnerUserService.findBy({
            query: {
                monitorId: monitorId,
            },
            select: {
                _id: true,
                user: {
                    _id: true,
                    email: true,
                    name: true,
                    timezone: true,
                },
            },
            props: {
                isRoot: true,
            },
            limit: LIMIT_PER_PROJECT,
            skip: 0,
        });
        const ownerTeams = await MonitorOwnerTeamService.findBy({
            query: {
                monitorId: monitorId,
            },
            select: {
                _id: true,
                teamId: true,
            },
            skip: 0,
            limit: LIMIT_PER_PROJECT,
            props: {
                isRoot: true,
            },
        });
        const users = ownerUsers.map((ownerUser) => {
            return ownerUser.user;
        }) || [];
        if (ownerTeams.length > 0) {
            const teamIds = ownerTeams.map((ownerTeam) => {
                return ownerTeam.teamId;
            }) || [];
            const teamUsers = await TeamMemberService.getUsersInTeams(teamIds);
            for (const teamUser of teamUsers) {
                //check if the user is already added.
                const isUserAlreadyAdded = users.find((user) => {
                    return user.id.toString() === teamUser.id.toString();
                });
                if (!isUserAlreadyAdded) {
                    users.push(teamUser);
                }
            }
        }
        return users;
    }
    async addOwners(projectId, monitorId, userIds, teamIds, notifyOwners, props) {
        for (let teamId of teamIds) {
            if (typeof teamId === Typeof.String) {
                teamId = new ObjectID(teamId.toString());
            }
            const teamOwner = new MonitorOwnerTeam();
            teamOwner.monitorId = monitorId;
            teamOwner.projectId = projectId;
            teamOwner.teamId = teamId;
            teamOwner.isOwnerNotified = !notifyOwners;
            await MonitorOwnerTeamService.create({
                data: teamOwner,
                props: props,
            });
        }
        for (let userId of userIds) {
            if (typeof userId === Typeof.String) {
                userId = new ObjectID(userId.toString());
            }
            const teamOwner = new MonitorOwnerUser();
            teamOwner.monitorId = monitorId;
            teamOwner.projectId = projectId;
            teamOwner.userId = userId;
            teamOwner.isOwnerNotified = !notifyOwners;
            await MonitorOwnerUserService.create({
                data: teamOwner,
                props: props,
            });
        }
    }
    async addDefaultProbesToMonitor(projectId, monitorId) {
        // Fetch project to see if global probes should be added automatically.
        const project = await ProjectService.findOneById({
            id: projectId,
            select: {
                _id: true,
                doNotAddGlobalProbesByDefaultOnNewMonitors: true,
            },
            props: {
                isRoot: true,
            },
        });
        const shouldSkipGlobalProbes = (project === null || project === void 0 ? void 0 : project.doNotAddGlobalProbesByDefaultOnNewMonitors) === true;
        let globalProbes = [];
        if (!shouldSkipGlobalProbes) {
            globalProbes = await ProbeService.findBy({
                query: {
                    isGlobalProbe: true,
                    shouldAutoEnableProbeOnNewMonitors: true,
                },
                select: {
                    _id: true,
                },
                skip: 0,
                limit: LIMIT_PER_PROJECT,
                props: {
                    isRoot: true,
                },
            });
        }
        const projectProbes = await ProbeService.findBy({
            query: {
                isGlobalProbe: false,
                shouldAutoEnableProbeOnNewMonitors: true,
                projectId: projectId,
            },
            select: {
                _id: true,
            },
            skip: 0,
            limit: LIMIT_PER_PROJECT,
            props: {
                isRoot: true,
            },
        });
        const totalProbes = [...globalProbes, ...projectProbes];
        if (totalProbes.length === 0) {
            return;
        }
        // Create all monitor probes in parallel for better performance
        const createPromises = [];
        for (const probe of totalProbes) {
            const monitorProbe = new MonitorProbe();
            monitorProbe.monitorId = monitorId;
            monitorProbe.probeId = probe.id;
            monitorProbe.projectId = projectId;
            monitorProbe.isEnabled = true;
            createPromises.push(MonitorProbeService.create({
                data: monitorProbe,
                props: {
                    isRoot: true,
                },
            }));
        }
        // Execute all creates in parallel
        await Promise.all(createPromises);
    }
    async refreshMonitorProbeStatus(monitorId) {
        const monitor = await this.findOneById({
            id: monitorId,
            select: {
                _id: true,
                monitorType: true,
                isAllProbesDisconnectedFromThisMonitor: true,
                isNoProbeEnabledOnThisMonitor: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!monitor) {
            return;
        }
        if (!monitor.id) {
            return;
        }
        const monitorType = monitor === null || monitor === void 0 ? void 0 : monitor.monitorType;
        if (!monitorType) {
            return;
        }
        const isProbeableMonitor = MonitorTypeHelper.isProbableMonitor(monitorType);
        if (!isProbeableMonitor) {
            return;
        }
        // get all the probes for this monitor.
        const probesForMonitor = await MonitorProbeService.findBy({
            query: {
                monitorId: monitorId,
            },
            select: {
                _id: true,
                isEnabled: true,
                projectId: true,
                monitorId: true,
                probeId: true,
                probe: {
                    connectionStatus: true,
                    isGlobalProbe: true,
                },
            },
            skip: 0,
            limit: LIMIT_PER_PROJECT,
            props: {
                isRoot: true,
            },
        });
        const enabledProbes = probesForMonitor.filter((probe) => {
            return probe.isEnabled;
        });
        if (probesForMonitor.length === 0 || enabledProbes.length === 0) {
            if (!monitor.isNoProbeEnabledOnThisMonitor) {
                // no probes for this monitor.
                await this.updateOneById({
                    id: monitorId,
                    data: {
                        isNoProbeEnabledOnThisMonitor: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                // notify owners that no probe is enabled.
                await this.notifyOwnersWhenNoProbeIsEnabled({
                    monitorId: monitorId,
                    isNoProbesEnabled: true,
                });
            }
        }
        else if (monitor.isNoProbeEnabledOnThisMonitor) {
            await this.updateOneById({
                id: monitorId,
                data: {
                    isNoProbeEnabledOnThisMonitor: false,
                },
                props: {
                    isRoot: true,
                },
            });
            // notify owners that probes are now enabled.
            await this.notifyOwnersWhenNoProbeIsEnabled({
                monitorId: monitorId,
                isNoProbesEnabled: false,
            });
        }
        const disconnectedProbes = probesForMonitor.filter((monitorProbe) => {
            var _a;
            return (((_a = monitorProbe.probe) === null || _a === void 0 ? void 0 : _a.connectionStatus) ===
                ProbeConnectionStatus.Disconnected && monitorProbe.isEnabled);
        });
        if (IsBillingEnabled) {
            // check if these probes are global probes.
            const anyGlobalProbe = enabledProbes.some((monitorProbe) => {
                var _a;
                return ((_a = monitorProbe.probe) === null || _a === void 0 ? void 0 : _a.isGlobalProbe) === true;
            });
            if (anyGlobalProbe) {
                // do not notify if any global probe is disconnected.
                return;
            }
        }
        if (disconnectedProbes.length === enabledProbes.length &&
            enabledProbes.length > 0) {
            if (!monitor.isAllProbesDisconnectedFromThisMonitor) {
                // all probes are disconnected.
                await this.updateOneById({
                    id: monitorId,
                    data: {
                        isAllProbesDisconnectedFromThisMonitor: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                await this.notifyOwnersProbesDisconnected({
                    monitorId: monitorId,
                    isProbeDisconnected: true,
                });
            }
        }
        else if (monitor.isAllProbesDisconnectedFromThisMonitor) {
            await this.updateOneById({
                id: monitorId,
                data: {
                    isAllProbesDisconnectedFromThisMonitor: false,
                },
                props: {
                    isRoot: true,
                },
            });
            await this.notifyOwnersProbesDisconnected({
                monitorId: monitorId,
                isProbeDisconnected: false,
            });
        }
    }
    async getLabelsForMonitors(data) {
        if (data.monitorIds.length === 0) {
            return [];
        }
        const monitors = await this.findBy({
            query: {
                _id: QueryHelper.any(data.monitorIds),
            },
            select: {
                _id: true,
                name: true,
                labels: true,
            },
            props: {
                isRoot: true,
            },
            skip: 0,
            limit: LIMIT_PER_PROJECT,
        });
        const labels = [];
        for (const monitor of monitors) {
            if (monitor.labels) {
                for (const label of monitor.labels) {
                    const isLabelAlreadyAdded = labels.some((l) => {
                        return l.id.toString() === label.id.toString();
                    });
                    if (!isLabelAlreadyAdded) {
                        labels.push(label);
                    }
                }
            }
        }
        return labels;
    }
    async notifyOwnersWhenNoProbeIsEnabled(data) {
        const monitor = await this.findOneById({
            id: data.monitorId,
            select: {
                _id: true,
                projectId: true,
                name: true,
                project: {
                    name: true,
                },
                description: true,
                monitorType: true,
                monitorSteps: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!monitor) {
            return;
        }
        if (!monitor.id) {
            return;
        }
        let doesResourceHasOwners = true;
        let owners = await this.findOwners(monitor.id);
        if (owners.length === 0) {
            doesResourceHasOwners = false;
            // find project owners.
            owners = await ProjectService.getOwners(monitor.projectId);
        }
        if (owners.length === 0) {
            return;
        }
        const title = data.isNoProbesEnabled
            ? "No Probes Enabled. This monitor is not being monitored"
            : "Probes Enabled. This monitor is now being monitored.";
        const enabledStatus = data.isNoProbesEnabled
            ? "Disabled"
            : "Enabled";
        // Get monitor destination info using the helper function
        const destinationInfo = this.getMonitorDestinationInfo(monitor);
        const vars = {
            title: title,
            monitorName: monitor.name,
            currentStatus: enabledStatus,
            projectName: monitor.project.name,
            monitorDescription: await Markdown.convertToHTML(monitor.description || "", MarkdownContentType.Email),
            monitorViewLink: (await this.getMonitorLinkInDashboard(monitor.projectId, monitor.id)).toString(),
            monitorDestination: destinationInfo.monitorDestination,
            requestType: destinationInfo.requestType,
            monitorType: destinationInfo.monitorType,
        };
        if (doesResourceHasOwners === true) {
            vars["isOwner"] = "true";
        }
        for (const owner of owners) {
            // send email to the owner.
            const emailMessage = {
                templateType: EmailTemplateType.MonitorProbesStatus,
                vars: vars,
                subject: `[${enabledStatus} Monitor Probes] ${monitor.name}`,
            };
            const sms = {
                message: `This is a message from OneUptime. Probes for monitor ${monitor.name} is ${enabledStatus}. To unsubscribe from this notification go to User Settings in OneUptime Dashboard.`,
            };
            const callMessage = {
                data: [
                    {
                        sayMessage: `This is a message from OneUptime. Probes for monitor ${monitor.name} is ${enabledStatus}. To unsubscribe from this notification go to User Settings in OneUptime Dashboard. Good bye.`,
                    },
                ],
            };
            const eventType = NotificationSettingEventType.SEND_MONITOR_NOTIFICATION_WHEN_NO_PROBES_ARE_MONITORING_THE_MONITOR;
            const whatsAppMessage = createWhatsAppMessageFromTemplate({
                eventType,
                templateVariables: {
                    monitor_name: monitor.name,
                    probe_status: enabledStatus,
                    monitor_link: vars["monitorViewLink"] || "",
                },
            });
            await UserNotificationSettingService.sendUserNotification({
                userId: owner.id,
                projectId: monitor.projectId,
                emailEnvelope: emailMessage,
                smsMessage: sms,
                callRequestMessage: callMessage,
                pushNotificationMessage: PushNotificationUtil.createMonitorProbeStatusNotification({
                    title: "OneUptime: Monitor Probe Status",
                    body: `Probes for monitor ${monitor.name} is ${enabledStatus}`,
                    tag: "monitor-probe-status",
                    monitorId: monitor.id.toString(),
                    monitorName: monitor.name,
                }),
                whatsAppMessage,
                eventType,
                monitorId: monitor.id,
            });
        }
    }
    async notifyOwnersProbesDisconnected(data) {
        const monitor = await this.findOneById({
            id: data.monitorId,
            select: {
                _id: true,
                projectId: true,
                name: true,
                project: {
                    name: true,
                },
                description: true,
                monitorType: true,
                monitorSteps: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!monitor) {
            return;
        }
        if (!monitor.id) {
            return;
        }
        let doesResourceHasOwners = true;
        let owners = await this.findOwners(monitor.id);
        if (owners.length === 0) {
            doesResourceHasOwners = false;
            // find project owners.
            owners = await ProjectService.getOwners(monitor.projectId);
        }
        if (owners.length === 0) {
            return;
        }
        const status = data.isProbeDisconnected
            ? "Disconnected"
            : "Connected";
        // Get monitor destination info using the helper function
        const destinationInfo = this.getMonitorDestinationInfo(monitor);
        const vars = {
            title: `Probes for monitor ${monitor.name} is ${status}.`,
            monitorName: monitor.name,
            currentStatus: status,
            projectName: monitor.project.name,
            monitorDescription: await Markdown.convertToHTML(monitor.description || "", MarkdownContentType.Email),
            monitorViewLink: (await this.getMonitorLinkInDashboard(monitor.projectId, monitor.id)).toString(),
            monitorDestination: destinationInfo.monitorDestination,
            requestType: destinationInfo.requestType,
            monitorType: destinationInfo.monitorType,
        };
        if (doesResourceHasOwners === true) {
            vars["isOwner"] = "true";
        }
        for (const owner of owners) {
            // send email to the owner.
            const emailMessage = {
                templateType: EmailTemplateType.MonitorProbesStatus,
                vars: vars,
                subject: `[${status} Monitor Probes] ${monitor.name}`,
            };
            const sms = {
                message: `This is a message from OneUptime. Probes for monitor ${monitor.name} is ${status}. To unsubscribe from this notification go to User Settings in OneUptime Dashboard.`,
            };
            const callMessage = {
                data: [
                    {
                        sayMessage: `This is a message from OneUptime. New monitor was created ${monitor.name}. To unsubscribe from this notification go to User Settings in OneUptime Dashboard. Good bye.`,
                    },
                ],
            };
            const eventType = NotificationSettingEventType.SEND_MONITOR_NOTIFICATION_WHEN_PORBE_STATUS_CHANGES;
            const whatsAppMessage = createWhatsAppMessageFromTemplate({
                eventType,
                templateVariables: {
                    monitor_name: monitor.name,
                    probe_status: status,
                    monitor_link: vars["monitorViewLink"] || "",
                },
            });
            await UserNotificationSettingService.sendUserNotification({
                userId: owner.id,
                projectId: monitor.projectId,
                emailEnvelope: emailMessage,
                smsMessage: sms,
                callRequestMessage: callMessage,
                pushNotificationMessage: PushNotificationUtil.createMonitorCreatedNotification({
                    monitorName: monitor.name,
                    monitorId: monitor.id.toString(),
                }),
                whatsAppMessage,
                eventType,
                monitorId: monitor.id,
            });
        }
    }
    async refreshProbeStatus(probeId) {
        // get all the monitors for this probe.
        const monitorProbes = await MonitorProbeService.findBy({
            query: {
                probeId: probeId,
            },
            select: {
                _id: true,
                isEnabled: true,
                projectId: true,
                monitorId: true,
                monitor: {
                    monitorType: true,
                },
            },
            skip: 0,
            limit: LIMIT_PER_PROJECT,
            props: {
                isRoot: true,
            },
        });
        if (monitorProbes.length === 0) {
            return;
        }
        /*
         * Each monitor appears at most once for a given probeId (composite
         * unique on MonitorProbe), so concurrent refreshes operate on
         * disjoint rows and are safe to run in parallel.
         */
        await Promise.all(monitorProbes.map((monitorProbe) => {
            return this.refreshMonitorProbeStatus(monitorProbe.monitorId);
        }));
    }
    async changeMonitorStatus(projectId, monitorIds, monitorStatusId, notifyOwners, rootCause, statusChangeLog, props, startsAt) {
        for (const monitorId of monitorIds) {
            // get last monitor status timeline.
            const lastMonitorStatusTimeline = await MonitorStatusTimelineService.findOneBy({
                query: {
                    monitorId: monitorId,
                    projectId: projectId,
                },
                select: {
                    _id: true,
                    monitorStatusId: true,
                },
                sort: {
                    startsAt: SortOrder.Descending,
                },
                props: {
                    isRoot: true,
                },
            });
            if (lastMonitorStatusTimeline &&
                lastMonitorStatusTimeline.monitorStatusId &&
                lastMonitorStatusTimeline.monitorStatusId.toString() ===
                    monitorStatusId.toString()) {
                // status is same as last status. do not create new status timeline.
                continue;
            }
            const statusTimeline = new MonitorStatusTimeline();
            statusTimeline.monitorId = monitorId;
            statusTimeline.monitorStatusId = monitorStatusId;
            statusTimeline.projectId = projectId;
            statusTimeline.isOwnerNotified = !notifyOwners;
            if (statusChangeLog) {
                statusTimeline.statusChangeLog = statusChangeLog;
            }
            if (rootCause) {
                statusTimeline.rootCause = rootCause;
            }
            if (startsAt) {
                statusTimeline.startsAt = startsAt;
            }
            await MonitorStatusTimelineService.create({
                data: statusTimeline,
                props: props,
            });
        }
    }
    async getWorkspaceChannelForMonitor(data) {
        const monitor = await this.findOneById({
            id: data.monitorId,
            select: {
                postUpdatesToWorkspaceChannels: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!monitor) {
            throw new BadDataException(ExceptionMessages.MonitorNotFound);
        }
        return (monitor.postUpdatesToWorkspaceChannels || []).filter((channel) => {
            if (!data.workspaceType) {
                return true;
            }
            return channel.workspaceType === data.workspaceType;
        });
    }
    // get monitor name
    async getMonitorName(data) {
        const { monitorId } = data;
        const monitor = await this.findOneById({
            id: monitorId,
            select: {
                name: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!monitor) {
            throw new BadDataException(ExceptionMessages.MonitorNotFound);
        }
        return monitor.name || "";
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeDelete", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Array]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onDeleteSuccess", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Array]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onUpdateSuccess", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeCreate", 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]),
    __metadata("design:returntype", Promise)
], Service.prototype, "handleWorkspaceOperationsAsync", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID,
        ObjectID]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getMonitorLinkInDashboard", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID]),
    __metadata("design:returntype", Promise)
], Service.prototype, "findOwners", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID,
        ObjectID,
        Array,
        Array, Boolean, Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "addOwners", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID,
        ObjectID]),
    __metadata("design:returntype", Promise)
], Service.prototype, "addDefaultProbesToMonitor", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID]),
    __metadata("design:returntype", Promise)
], Service.prototype, "refreshMonitorProbeStatus", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getLabelsForMonitors", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "notifyOwnersWhenNoProbeIsEnabled", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "notifyOwnersProbesDisconnected", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID]),
    __metadata("design:returntype", Promise)
], Service.prototype, "refreshProbeStatus", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID,
        Array,
        ObjectID, Boolean, Object, Object, Object, Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "changeMonitorStatus", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getWorkspaceChannelForMonitor", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getMonitorName", null);
export default new Service();
//# sourceMappingURL=MonitorService.js.map