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 DockerHost from "../../../Models/DatabaseModels/DockerHost";
import Host from "../../../Models/DatabaseModels/Host";
import Incident from "../../../Models/DatabaseModels/Incident";
import IncidentStateTimeline from "../../../Models/DatabaseModels/IncidentStateTimeline";
import IncidentMember from "../../../Models/DatabaseModels/IncidentMember";
import KubernetesCluster from "../../../Models/DatabaseModels/KubernetesCluster";
import Label from "../../../Models/DatabaseModels/Label";
import OnCallDutyPolicy from "../../../Models/DatabaseModels/OnCallDutyPolicy";
import Service from "../../../Models/DatabaseModels/Service";
import Includes from "../../../Types/BaseDatabase/Includes";
import SortOrder from "../../../Types/BaseDatabase/SortOrder";
import { LIMIT_PER_PROJECT } from "../../../Types/Database/LimitMax";
import BadDataException from "../../../Types/Exception/BadDataException";
import ObjectID from "../../../Types/ObjectID";
import { DisableAutomaticIncidentCreation } from "../../EnvironmentConfig";
import DockerHostService from "../../Services/DockerHostService";
import HostService from "../../Services/HostService";
import IncidentService from "../../Services/IncidentService";
import KubernetesClusterService from "../../Services/KubernetesClusterService";
import ServiceService from "../../Services/ServiceService";
import IncidentSeverityService from "../../Services/IncidentSeverityService";
import IncidentStateTimelineService from "../../Services/IncidentStateTimelineService";
import IncidentMemberService from "../../Services/IncidentMemberService";
import logger from "../Logger";
import CaptureSpan from "../Telemetry/CaptureSpan";
import MonitorTemplateUtil from "./MonitorTemplateUtil";
import OneUptimeDate from "../../../Types/Date";
import SeriesResourceLabels from "./SeriesResourceLabels";
export default class MonitorIncident {
    static async checkOpenIncidentsAndCloseIfResolved(input) {
        var _a, _b, _c, _d, _e;
        // check active incidents and if there are open incidents, do not create another incident.
        const openIncidents = await IncidentService.findBy({
            query: {
                monitors: [input.monitorId],
                currentIncidentState: {
                    isResolvedState: false,
                },
            },
            skip: 0,
            limit: LIMIT_PER_PROJECT,
            select: {
                _id: true,
                title: true,
                createdCriteriaId: true,
                createdIncidentTemplateId: true,
                projectId: true,
                incidentNumber: true,
                incidentNumberWithPrefix: true,
                currentIncidentStateId: true,
                seriesFingerprint: true,
                seriesLabels: true,
            },
            props: {
                isRoot: true,
            },
        });
        // check if should close the incident.
        for (const openIncident of openIncidents) {
            const shouldClose = this.shouldCloseIncident({
                openIncident,
                autoResolveCriteriaInstanceIdIncidentIdsDictionary: input.autoResolveCriteriaInstanceIdIncidentIdsDictionary,
                criteriaInstance: input.criteriaInstance,
                breachingSeriesFingerprints: input.breachingSeriesFingerprints,
            });
            if (shouldClose) {
                // then resolve incident.
                await this.resolveOpenIncident({
                    openIncident: openIncident,
                    rootCause: input.rootCause,
                    dataToProcess: input.dataToProcess,
                });
                (_a = input.evaluationSummary) === null || _a === void 0 ? void 0 : _a.events.push({
                    type: "incident-resolved",
                    title: `Incident resolved: ${(_b = openIncident.id) === null || _b === void 0 ? void 0 : _b.toString()}`,
                    message: "Incident auto-resolved because autoresolve is enabled for this criteria.",
                    relatedIncidentId: (_c = openIncident.id) === null || _c === void 0 ? void 0 : _c.toString(),
                    relatedIncidentNumber: openIncident.incidentNumber,
                    relatedIncidentNumberWithPrefix: openIncident.incidentNumberWithPrefix,
                    relatedCriteriaId: (_e = (_d = input.criteriaInstance) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.id,
                    at: OneUptimeDate.getCurrentDate(),
                });
            }
        }
        return openIncidents;
    }
    static async criteriaMetCreateIncidentsAndUpdateMonitorStatus(input) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3;
        const incidentLogAttributes = {
            projectId: (_a = input.monitor.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
        };
        // check open incidents
        logger.debug(`${(_b = input.monitor.id) === null || _b === void 0 ? void 0 : _b.toString()} - Check open incidents.`, incidentLogAttributes);
        /*
         * Per-series mode: close any open incident for a series that's no
         * longer breaching *before* we look at the remaining open set, so
         * dedupe decisions below match the post-resolve state.
         */
        const breachingSeriesFingerprints = input.matchesPerSeries
            ? new Set(input.matchesPerSeries.map((m) => {
                return m.fingerprint;
            }))
            : undefined;
        // check active incidents and if there are open incidents, do not cretae anothr incident.
        const openIncidents = await this.checkOpenIncidentsAndCloseIfResolved({
            monitorId: input.monitor.id,
            autoResolveCriteriaInstanceIdIncidentIdsDictionary: input.autoResolveCriteriaInstanceIdIncidentIdsDictionary,
            rootCause: input.rootCause,
            criteriaInstance: input.criteriaInstance,
            dataToProcess: input.dataToProcess,
            evaluationSummary: input.evaluationSummary,
            breachingSeriesFingerprints,
        });
        if (!((_c = input.criteriaInstance.data) === null || _c === void 0 ? void 0 : _c.createIncidents)) {
            return;
        }
        /*
         * Series-less path: one incident per criteriaIncident template as
         * before. Series-aware path: one incident per (series × template).
         */
        const seriesToProcess = input.matchesPerSeries && input.matchesPerSeries.length > 0
            ? input.matchesPerSeries
            : [undefined];
        for (const criteriaIncident of ((_d = input.criteriaInstance.data) === null || _d === void 0 ? void 0 : _d.incidents) ||
            []) {
            for (const seriesMatch of seriesToProcess) {
                const seriesFingerprint = seriesMatch === null || seriesMatch === void 0 ? void 0 : seriesMatch.fingerprint;
                const seriesLabels = seriesMatch === null || seriesMatch === void 0 ? void 0 : seriesMatch.labels;
                const seriesRootCause = (seriesMatch === null || seriesMatch === void 0 ? void 0 : seriesMatch.rootCause) || input.rootCause;
                /*
                 * Per-series scheduled-maintenance suppression: this series'
                 * resource is inside an ongoing maintenance window, so skip
                 * creating an incident for it. Other series on the same monitor
                 * whose resources are not under maintenance still get incidents.
                 * Note: we only suppress *new* creation — any incident already
                 * open for this series is left to the normal resolve path
                 * (checkOpenIncidentsAndCloseIfResolved still sees the full
                 * breaching set), so a real incident raised before maintenance
                 * is not silently closed.
                 */
                if (seriesFingerprint &&
                    ((_e = input.suppressedSeriesFingerprints) === null || _e === void 0 ? void 0 : _e.has(seriesFingerprint))) {
                    logger.debug(`${(_f = input.monitor.id) === null || _f === void 0 ? void 0 : _f.toString()} - Skipping incident for series ${seriesFingerprint}: its resource is under an active scheduled maintenance window.`, incidentLogAttributes);
                    (_g = input.evaluationSummary) === null || _g === void 0 ? void 0 : _g.events.push({
                        type: "incident-skipped",
                        title: "Incident suppressed by scheduled maintenance",
                        message: "Skipped creating an incident because the resource for this series is under an active scheduled maintenance window.",
                        relatedCriteriaId: (_h = input.criteriaInstance.data) === null || _h === void 0 ? void 0 : _h.id,
                        at: OneUptimeDate.getCurrentDate(),
                    });
                    continue;
                }
                const alreadyOpenIncident = openIncidents.find((incident) => {
                    var _a;
                    return (incident.createdCriteriaId ===
                        ((_a = input.criteriaInstance.data) === null || _a === void 0 ? void 0 : _a.id.toString()) &&
                        incident.createdIncidentTemplateId ===
                            criteriaIncident.id.toString() &&
                        (incident.seriesFingerprint || undefined) === seriesFingerprint);
                });
                const hasAlreadyOpenIncident = Boolean(alreadyOpenIncident);
                logger.debug(`${(_j = input.monitor.id) === null || _j === void 0 ? void 0 : _j.toString()} - Open Incident ${(_k = alreadyOpenIncident === null || alreadyOpenIncident === void 0 ? void 0 : alreadyOpenIncident.id) === null || _k === void 0 ? void 0 : _k.toString()}`, incidentLogAttributes);
                logger.debug(`${(_l = input.monitor.id) === null || _l === void 0 ? void 0 : _l.toString()} - Has open incident ${hasAlreadyOpenIncident}`, incidentLogAttributes);
                if (hasAlreadyOpenIncident) {
                    /*
                     * Use the open incident's already-rendered title when
                     * available — the template (`criteriaIncident.title`) still
                     * contains unresolved `{{…}}` placeholders because it's the
                     * criterion's template string, not the instance's rendered
                     * output. Falling back to the template only when the open
                     * incident somehow has no title.
                     */
                    const renderedTitle = (alreadyOpenIncident === null || alreadyOpenIncident === void 0 ? void 0 : alreadyOpenIncident.title) || criteriaIncident.title;
                    (_m = input.evaluationSummary) === null || _m === void 0 ? void 0 : _m.events.push({
                        type: "incident-skipped",
                        title: `Incident already active: ${renderedTitle}`,
                        message: "Skipped creating a new incident because an active incident exists for this criteria.",
                        relatedCriteriaId: (_o = input.criteriaInstance.data) === null || _o === void 0 ? void 0 : _o.id,
                        relatedIncidentId: (_p = alreadyOpenIncident === null || alreadyOpenIncident === void 0 ? void 0 : alreadyOpenIncident.id) === null || _p === void 0 ? void 0 : _p.toString(),
                        relatedIncidentNumber: alreadyOpenIncident === null || alreadyOpenIncident === void 0 ? void 0 : alreadyOpenIncident.incidentNumber,
                        relatedIncidentNumberWithPrefix: alreadyOpenIncident === null || alreadyOpenIncident === void 0 ? void 0 : alreadyOpenIncident.incidentNumberWithPrefix,
                        at: OneUptimeDate.getCurrentDate(),
                    });
                    continue;
                }
                logger.debug(`${(_q = input.monitor.id) === null || _q === void 0 ? void 0 : _q.toString()} - Create incident.`, incidentLogAttributes);
                const incident = new Incident();
                const storageMap = MonitorTemplateUtil.buildTemplateStorageMap({
                    monitorType: input.monitor.monitorType,
                    dataToProcess: input.dataToProcess,
                    monitor: input.monitor,
                    seriesLabels,
                });
                incident.title = MonitorTemplateUtil.processTemplateString({
                    value: criteriaIncident.title,
                    storageMap,
                });
                incident.description = MonitorTemplateUtil.processTemplateString({
                    value: criteriaIncident.description,
                    storageMap,
                });
                if (!criteriaIncident.incidentSeverityId) {
                    // pick the critical criteria.
                    const severity = await IncidentSeverityService.findOneBy({
                        query: {
                            projectId: input.monitor.projectId,
                        },
                        sort: {
                            order: SortOrder.Ascending,
                        },
                        props: {
                            isRoot: true,
                        },
                        select: {
                            _id: true,
                        },
                    });
                    if (!severity) {
                        throw new BadDataException("Project does not have incident severity");
                    }
                    else {
                        incident.incidentSeverityId = severity.id;
                    }
                }
                else {
                    incident.incidentSeverityId = criteriaIncident.incidentSeverityId;
                }
                incident.monitors = [input.monitor];
                incident.projectId = input.monitor.projectId;
                incident.rootCause = seriesRootCause;
                incident.createdStateLog = JSON.parse(JSON.stringify(input.dataToProcess, null, 2));
                /*
                 * Guard against missing ids — these are optional reference fields and
                 * must not crash incident creation (which runs inside the probe /
                 * telemetry queue workers). A missing id previously threw
                 * "Cannot read properties of undefined (reading 'toString')" and failed
                 * the job on every cycle for the affected monitor.
                 */
                if ((_r = input.criteriaInstance.data) === null || _r === void 0 ? void 0 : _r.id) {
                    incident.createdCriteriaId =
                        input.criteriaInstance.data.id.toString();
                }
                if (criteriaIncident.id) {
                    incident.createdIncidentTemplateId = criteriaIncident.id.toString();
                }
                if (seriesFingerprint) {
                    incident.seriesFingerprint = seriesFingerprint;
                }
                if (seriesLabels && Object.keys(seriesLabels).length > 0) {
                    incident.seriesLabels = seriesLabels;
                    await this.linkResourceContextFromSeries({
                        incident,
                        seriesLabels,
                        projectId: input.monitor.projectId,
                    });
                }
                incident.onCallDutyPolicies =
                    ((_s = criteriaIncident.onCallPolicyIds) === null || _s === void 0 ? void 0 : _s.map((id) => {
                        const onCallPolicy = new OnCallDutyPolicy();
                        onCallPolicy._id = id.toString();
                        return onCallPolicy;
                    })) || [];
                // Set labels from criteria
                incident.labels =
                    ((_t = criteriaIncident.labelIds) === null || _t === void 0 ? void 0 : _t.map((id) => {
                        const label = new Label();
                        label._id = id.toString();
                        return label;
                    })) || [];
                incident.isCreatedAutomatically = true;
                // Set status page visibility (defaults to true if not specified)
                if (criteriaIncident.showIncidentOnStatusPage !== undefined) {
                    incident.isVisibleOnStatusPage =
                        criteriaIncident.showIncidentOnStatusPage;
                }
                if (criteriaIncident.isPrivate === true) {
                    incident.isPrivate = true;
                }
                if (input.props.telemetryQuery) {
                    incident.telemetryQuery = input.props.telemetryQuery;
                }
                if (input.dataToProcess &&
                    input.dataToProcess.probeId) {
                    incident.createdByProbeId = input.dataToProcess.probeId;
                }
                if (criteriaIncident.remediationNotes) {
                    incident.remediationNotes = MonitorTemplateUtil.processTemplateString({
                        value: criteriaIncident.remediationNotes,
                        storageMap,
                    });
                }
                if (DisableAutomaticIncidentCreation) {
                    (_u = input.evaluationSummary) === null || _u === void 0 ? void 0 : _u.events.push({
                        type: "incident-skipped",
                        title: "Incident creation skipped",
                        message: "Automatic incident creation is disabled by environment configuration.",
                        relatedCriteriaId: (_v = input.criteriaInstance.data) === null || _v === void 0 ? void 0 : _v.id,
                        at: OneUptimeDate.getCurrentDate(),
                    });
                    return;
                }
                const createdIncident = await IncidentService.create({
                    data: incident,
                    props: {
                        isRoot: true,
                    },
                });
                // Add owner teams and users after incident creation
                if (((_w = criteriaIncident.ownerTeamIds) === null || _w === void 0 ? void 0 : _w.length) ||
                    ((_x = criteriaIncident.ownerUserIds) === null || _x === void 0 ? void 0 : _x.length)) {
                    await IncidentService.addOwners(input.monitor.projectId, createdIncident.id, criteriaIncident.ownerUserIds || [], criteriaIncident.ownerTeamIds || [], true, // notify owners
                    {
                        isRoot: true,
                    });
                }
                // Add incident member role assignments after incident creation
                if (criteriaIncident.incidentMemberRoles &&
                    criteriaIncident.incidentMemberRoles.length > 0) {
                    for (const roleAssignment of criteriaIncident.incidentMemberRoles) {
                        try {
                            const assignment = roleAssignment;
                            if (assignment.roleId && assignment.userId) {
                                const incidentMember = new IncidentMember();
                                incidentMember.incidentId = createdIncident.id;
                                incidentMember.projectId = input.monitor.projectId;
                                incidentMember.userId = new ObjectID(assignment.userId.toString());
                                incidentMember.incidentRoleId = new ObjectID(assignment.roleId.toString());
                                await IncidentMemberService.create({
                                    data: incidentMember,
                                    props: {
                                        isRoot: true,
                                    },
                                });
                                logger.debug(`${(_y = input.monitor.id) === null || _y === void 0 ? void 0 : _y.toString()} - Assigned incident member role ${assignment.roleId.toString()} to user ${assignment.userId.toString()}`, incidentLogAttributes);
                            }
                        }
                        catch (memberError) {
                            logger.error(`${(_z = input.monitor.id) === null || _z === void 0 ? void 0 : _z.toString()} - Failed to assign incident member role: ${memberError}`, incidentLogAttributes);
                        }
                    }
                }
                (_0 = input.evaluationSummary) === null || _0 === void 0 ? void 0 : _0.events.push({
                    type: "incident-created",
                    title: `Incident created: ${createdIncident.title || criteriaIncident.title}`,
                    message: `Incident triggered from criteria "${((_1 = input.criteriaInstance.data) === null || _1 === void 0 ? void 0 : _1.name) || "Unnamed criteria"}".`,
                    relatedCriteriaId: (_2 = input.criteriaInstance.data) === null || _2 === void 0 ? void 0 : _2.id,
                    relatedIncidentId: (_3 = createdIncident.id) === null || _3 === void 0 ? void 0 : _3.toString(),
                    relatedIncidentNumber: createdIncident.incidentNumber,
                    relatedIncidentNumberWithPrefix: createdIncident.incidentNumberWithPrefix,
                    at: OneUptimeDate.getCurrentDate(),
                });
            }
        }
    }
    /*
     * Pull every host / docker-host / k8s-cluster / service identifier
     * out of the series labels and attach the matching project-scoped
     * records to the incident. The label-key → resource-type mapping
     * lives in SeriesResourceLabels (shared with the scheduled-maintenance
     * suppression path so the two never disagree about which labels
     * identify which resource). Lookups are always project-scoped so a
     * stale or hostile stamp can't pull in a record from another tenant.
     */
    static async linkResourceContextFromSeries(input) {
        const refs = SeriesResourceLabels.extractResourceRefs(input.seriesLabels);
        const [resolvedHosts, resolvedDockerHosts, resolvedClusters, resolvedServices,] = await Promise.all([
            this.resolveResourceIds({
                ids: refs.hostIds,
                names: refs.hostNames,
                nameColumn: "hostIdentifier",
                projectId: input.projectId,
                findBy: HostService.findBy.bind(HostService),
            }),
            this.resolveResourceIds({
                ids: refs.dockerHostIds,
                names: refs.dockerHostNames,
                nameColumn: "hostIdentifier",
                projectId: input.projectId,
                findBy: DockerHostService.findBy.bind(DockerHostService),
            }),
            this.resolveResourceIds({
                ids: refs.kubernetesClusterIds,
                names: refs.kubernetesClusterNames,
                nameColumn: "clusterIdentifier",
                projectId: input.projectId,
                findBy: KubernetesClusterService.findBy.bind(KubernetesClusterService),
            }),
            this.resolveResourceIds({
                ids: refs.serviceIds,
                names: refs.serviceNames,
                nameColumn: "name",
                projectId: input.projectId,
                findBy: ServiceService.findBy.bind(ServiceService),
            }),
        ]);
        if (resolvedHosts.length > 0) {
            input.incident.hosts = resolvedHosts.map((id) => {
                const host = new Host();
                host._id = id;
                return host;
            });
        }
        if (resolvedDockerHosts.length > 0) {
            input.incident.dockerHosts = resolvedDockerHosts.map((id) => {
                const dockerHost = new DockerHost();
                dockerHost._id = id;
                return dockerHost;
            });
        }
        if (resolvedClusters.length > 0) {
            input.incident.kubernetesClusters = resolvedClusters.map((id) => {
                const cluster = new KubernetesCluster();
                cluster._id = id;
                return cluster;
            });
        }
        if (resolvedServices.length > 0) {
            input.incident.services = resolvedServices.map((id) => {
                const service = new Service();
                service._id = id;
                return service;
            });
        }
    }
    /*
     * Resolve a mix of ids and names to a deduped set of database ids
     * for one resource type, project-scoped. Either or both lists may
     * be empty; if both are empty the method short-circuits with no DB
     * round-trip.
     */
    static async resolveResourceIds(input) {
        if (input.ids.length === 0 && input.names.length === 0) {
            return [];
        }
        const resolved = new Set();
        const lookups = [];
        if (input.ids.length > 0) {
            lookups.push(input.findBy({
                query: {
                    projectId: input.projectId,
                    _id: new Includes(input.ids),
                },
                select: { _id: true },
                skip: 0,
                limit: LIMIT_PER_PROJECT,
                props: { isRoot: true },
            }));
        }
        if (input.names.length > 0) {
            lookups.push(input.findBy({
                query: {
                    projectId: input.projectId,
                    [input.nameColumn]: new Includes(input.names),
                },
                select: { _id: true },
                skip: 0,
                limit: LIMIT_PER_PROJECT,
                props: { isRoot: true },
            }));
        }
        const buckets = await Promise.all(lookups);
        for (const bucket of buckets) {
            for (const row of bucket) {
                if (row._id) {
                    resolved.add(String(row._id));
                }
            }
        }
        return Array.from(resolved);
    }
    static async resolveOpenIncident(input) {
        const resolvedStateId = await IncidentStateTimelineService.getResolvedStateIdForProject(input.openIncident.projectId);
        const incidentStateTimeline = new IncidentStateTimeline();
        incidentStateTimeline.incidentId = input.openIncident.id;
        incidentStateTimeline.incidentStateId = resolvedStateId;
        incidentStateTimeline.projectId = input.openIncident.projectId;
        if (input.rootCause) {
            incidentStateTimeline.rootCause =
                "Incident autoresolved because autoresolve is set to true in monitor criteria. " +
                    input.rootCause;
        }
        if (input.dataToProcess) {
            incidentStateTimeline.stateChangeLog = JSON.parse(JSON.stringify(input.dataToProcess));
        }
        await IncidentStateTimelineService.create({
            data: incidentStateTimeline,
            props: {
                isRoot: true,
            },
        });
    }
    static shouldCloseIncident(input) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
        const openSeriesFingerprint = input.openIncident.seriesFingerprint || undefined;
        /*
         * Per-series auto-resolve: when the monitor emits a breaching-
         * series set and this open incident has a fingerprint, resolve
         * whenever the fingerprint is no longer in the set — regardless
         * of whether some *other* series is still breaching the same
         * criteria. This is the whole point of per-host incidents.
         */
        if (input.breachingSeriesFingerprints !== undefined &&
            openSeriesFingerprint) {
            const stillBreaching = input.breachingSeriesFingerprints.has(openSeriesFingerprint);
            if (stillBreaching) {
                return false;
            }
            /*
             * Series no longer breaching. Only auto-close if the criteria
             * was configured to auto-resolve in the first place; otherwise
             * stay open so a human can acknowledge.
             */
            if (!((_a = input.openIncident.createdCriteriaId) === null || _a === void 0 ? void 0 : _a.toString())) {
                return false;
            }
            if (!((_b = input.openIncident.createdIncidentTemplateId) === null || _b === void 0 ? void 0 : _b.toString())) {
                return false;
            }
            const autoResolveTemplates = input.autoResolveCriteriaInstanceIdIncidentIdsDictionary[input.openIncident.createdCriteriaId.toString()];
            if (autoResolveTemplates &&
                autoResolveTemplates.includes(input.openIncident.createdIncidentTemplateId.toString())) {
                return true;
            }
            return false;
        }
        if (((_c = input.openIncident.createdCriteriaId) === null || _c === void 0 ? void 0 : _c.toString()) ===
            ((_e = (_d = input.criteriaInstance) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.id.toString())) {
            // same incident active. So, do not close.
            return false;
        }
        // If antoher criteria is active then, check if the incident id is present in the map.
        if (!((_f = input.openIncident.createdCriteriaId) === null || _f === void 0 ? void 0 : _f.toString())) {
            return false;
        }
        if (!((_g = input.openIncident.createdIncidentTemplateId) === null || _g === void 0 ? void 0 : _g.toString())) {
            return false;
        }
        if (input.autoResolveCriteriaInstanceIdIncidentIdsDictionary[(_h = input.openIncident.createdCriteriaId) === null || _h === void 0 ? void 0 : _h.toString()]) {
            if ((_k = input.autoResolveCriteriaInstanceIdIncidentIdsDictionary[(_j = input.openIncident.createdCriteriaId) === null || _j === void 0 ? void 0 : _j.toString()]) === null || _k === void 0 ? void 0 : _k.includes((_l = input.openIncident.createdIncidentTemplateId) === null || _l === void 0 ? void 0 : _l.toString())) {
                return true;
            }
        }
        return false;
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MonitorIncident, "checkOpenIncidentsAndCloseIfResolved", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MonitorIncident, "criteriaMetCreateIncidentsAndUpdateMonitorStatus", null);
//# sourceMappingURL=MonitorIncident.js.map