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/MonitorOwnerTeam";
import MonitorFeedService from "./MonitorFeedService";
import { MonitorFeedEventType } from "../../Models/DatabaseModels/MonitorFeed";
import { Gray500, Red500 } from "../../Types/BrandColors";
import TeamService from "./TeamService";
import MonitorService from "./MonitorService";
import WorkspaceNotificationRuleService from "./WorkspaceNotificationRuleService";
import NotificationRuleEventType from "../../Types/Workspace/NotificationRules/EventType";
import logger from "../Utils/Logger";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeDelete(deleteBy) {
        const itemsToDelete = await this.findBy({
            query: deleteBy.query,
            limit: deleteBy.limit,
            skip: deleteBy.skip,
            props: {
                isRoot: true,
            },
            select: {
                monitorId: true,
                projectId: true,
                teamId: true,
            },
        });
        return {
            carryForward: {
                itemsToDelete: itemsToDelete,
            },
            deleteBy: deleteBy,
        };
    }
    async onDeleteSuccess(onDelete, _itemIdsBeforeDelete) {
        var _a;
        const deleteByUserId = ((_a = onDelete.deleteBy.deletedByUser) === null || _a === void 0 ? void 0 : _a.id) || onDelete.deleteBy.props.userId;
        const itemsToDelete = onDelete.carryForward.itemsToDelete;
        for (const item of itemsToDelete) {
            const monitorId = item.monitorId;
            const projectId = item.projectId;
            const teamId = item.teamId;
            if (monitorId && teamId && projectId) {
                const team = await TeamService.findOneById({
                    id: teamId,
                    select: {
                        name: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                const monitorName = await MonitorService.getMonitorName({
                    monitorId: monitorId,
                });
                if (team && team.name) {
                    await MonitorFeedService.createMonitorFeedItem({
                        monitorId: monitorId,
                        projectId: projectId,
                        monitorFeedEventType: MonitorFeedEventType.OwnerTeamRemoved,
                        displayColor: Red500,
                        feedInfoInMarkdown: `👨🏻‍👩🏻‍👦🏻 Removed team **${team.name}** from the [Monitor ${monitorName}](${(await MonitorService.getMonitorLinkInDashboard(projectId, monitorId)).toString()}) as the owner.`,
                        userId: deleteByUserId || undefined,
                        workspaceNotification: {
                            sendWorkspaceNotification: true,
                            notifyUserId: deleteByUserId || undefined,
                        },
                    });
                }
            }
        }
        return onDelete;
    }
    async onCreateSuccess(onCreate, createdItem) {
        // add monitor feed.
        const monitorId = createdItem.monitorId;
        const projectId = createdItem.projectId;
        const teamId = createdItem.teamId;
        const createdByUserId = createdItem.createdByUserId || onCreate.createBy.props.userId;
        if (monitorId && teamId && projectId) {
            const team = await TeamService.findOneById({
                id: teamId,
                select: {
                    name: true,
                },
                props: {
                    isRoot: true,
                },
            });
            if (team && team.name) {
                const monitorName = await MonitorService.getMonitorName({
                    monitorId: monitorId,
                });
                await MonitorFeedService.createMonitorFeedItem({
                    monitorId: monitorId,
                    projectId: projectId,
                    monitorFeedEventType: MonitorFeedEventType.OwnerTeamAdded,
                    displayColor: Gray500,
                    feedInfoInMarkdown: `👨🏻‍👩🏻‍👦🏻 Added team **${team.name}** to the [Monitor ${monitorName}](${(await MonitorService.getMonitorLinkInDashboard(projectId, monitorId)).toString()}) as the owner.`,
                    userId: createdByUserId || undefined,
                    workspaceNotification: {
                        sendWorkspaceNotification: true,
                        notifyUserId: createdByUserId || undefined,
                    },
                });
            }
        }
        // get notification rule where inviteOwners is true.
        const notificationRules = await WorkspaceNotificationRuleService.getNotificationRulesWhereInviteOwnersIsTrue({
            projectId: projectId,
            notificationFor: {
                monitorId: monitorId,
            },
            notificationRuleEventType: NotificationRuleEventType.Monitor,
        });
        logger.debug(`Notification Rules for Monitor Owner Teams`);
        logger.debug(notificationRules);
        WorkspaceNotificationRuleService.inviteTeamsBasedOnRulesAndWorkspaceChannels({
            notificationRules: notificationRules,
            projectId: projectId,
            workspaceChannels: await MonitorService.getWorkspaceChannelForMonitor({
                monitorId: monitorId,
            }),
            teamIds: [teamId],
        }).catch((error) => {
            logger.error(error);
        });
        return createdItem;
    }
}
__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, Model]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onCreateSuccess", null);
export default new Service();
//# sourceMappingURL=MonitorOwnerTeamService.js.map