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/IncidentEpisodeOwnerUser";
import IncidentEpisodeFeedService from "./IncidentEpisodeFeedService";
import { IncidentEpisodeFeedEventType } from "../../Models/DatabaseModels/IncidentEpisodeFeed";
import { Gray500, Red500 } from "../../Types/BrandColors";
import UserService from "./UserService";
import IncidentEpisodeService from "./IncidentEpisodeService";
import WorkspaceNotificationRuleService from "./WorkspaceNotificationRuleService";
import NotificationRuleEventType from "../../Types/Workspace/NotificationRules/EventType";
import { applyIncidentEpisodeRelatedRecordPrivacyFilter } from "../Utils/IncidentEpisode/IncidentEpisodePrivacyFilter";
import logger from "../Utils/Logger";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeFind(findBy) {
        findBy.query = applyIncidentEpisodeRelatedRecordPrivacyFilter(findBy.query, findBy.props);
        return { findBy, carryForward: null };
    }
    async countBy(countBy) {
        countBy.query = applyIncidentEpisodeRelatedRecordPrivacyFilter(countBy.query, countBy.props);
        return super.countBy(countBy);
    }
    async onBeforeUpdate(updateBy) {
        updateBy.query = applyIncidentEpisodeRelatedRecordPrivacyFilter(updateBy.query, updateBy.props);
        return { updateBy, carryForward: null };
    }
    async onBeforeDelete(deleteBy) {
        deleteBy.query = applyIncidentEpisodeRelatedRecordPrivacyFilter(deleteBy.query, deleteBy.props);
        const itemsToDelete = await this.findBy({
            query: deleteBy.query,
            limit: deleteBy.limit,
            skip: deleteBy.skip,
            props: {
                isRoot: true,
            },
            select: {
                incidentEpisodeId: true,
                projectId: true,
                userId: true,
            },
        });
        return {
            carryForward: {
                itemsToDelete: itemsToDelete,
            },
            deleteBy: deleteBy,
        };
    }
    async onDeleteSuccess(onDelete, _itemIdsBeforeDelete) {
        var _a, _b;
        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 incidentEpisodeId = item.incidentEpisodeId;
            const projectId = item.projectId;
            const userId = item.userId;
            if (incidentEpisodeId && userId && projectId) {
                const user = await UserService.findOneById({
                    id: userId,
                    select: {
                        name: true,
                        email: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                const episodeNumberResult = await IncidentEpisodeService.getEpisodeNumber({
                    episodeId: incidentEpisodeId,
                });
                const episodeNumberDisplay = episodeNumberResult.numberWithPrefix ||
                    "#" + episodeNumberResult.number;
                if (user && user.name) {
                    await IncidentEpisodeFeedService.createIncidentEpisodeFeedItem({
                        incidentEpisodeId: incidentEpisodeId,
                        projectId: projectId,
                        incidentEpisodeFeedEventType: IncidentEpisodeFeedEventType.OwnerUserRemoved,
                        displayColor: Red500,
                        feedInfoInMarkdown: `👨🏻‍💻 Removed **${user.name.toString()}** (${(_b = user.email) === null || _b === void 0 ? void 0 : _b.toString()}) from the [Episode ${episodeNumberDisplay}](${(await IncidentEpisodeService.getEpisodeLinkInDashboard(projectId, incidentEpisodeId)).toString()}) as the owner.`,
                        userId: deleteByUserId || undefined,
                        workspaceNotification: {
                            sendWorkspaceNotification: true,
                            notifyUserId: userId || undefined,
                        },
                    });
                }
            }
        }
        return onDelete;
    }
    async onCreateSuccess(onCreate, createdItem) {
        const incidentEpisodeId = createdItem.incidentEpisodeId;
        const projectId = createdItem.projectId;
        const userId = createdItem.userId;
        const createdByUserId = createdItem.createdByUserId || onCreate.createBy.props.userId;
        if (incidentEpisodeId && userId && projectId) {
            const episodeNumberResult = await IncidentEpisodeService.getEpisodeNumber({
                episodeId: incidentEpisodeId,
            });
            const episodeNumberDisplay = episodeNumberResult.numberWithPrefix ||
                "#" + episodeNumberResult.number;
            await IncidentEpisodeFeedService.createIncidentEpisodeFeedItem({
                incidentEpisodeId: incidentEpisodeId,
                projectId: projectId,
                incidentEpisodeFeedEventType: IncidentEpisodeFeedEventType.OwnerUserAdded,
                displayColor: Gray500,
                feedInfoInMarkdown: `👨🏻‍💻 Added **${await UserService.getUserMarkdownString({
                    userId: userId,
                    projectId: projectId,
                })}** to the [Episode ${episodeNumberDisplay}](${(await IncidentEpisodeService.getEpisodeLinkInDashboard(projectId, incidentEpisodeId)).toString()}) as the owner.`,
                userId: createdByUserId || undefined,
                workspaceNotification: {
                    sendWorkspaceNotification: true,
                    notifyUserId: userId || undefined,
                },
            });
            // get notification rule where inviteOwners is true.
            const notificationRules = await WorkspaceNotificationRuleService.getNotificationRulesWhereInviteOwnersIsTrue({
                projectId: projectId,
                notificationFor: {
                    incidentEpisodeId: incidentEpisodeId,
                },
                notificationRuleEventType: NotificationRuleEventType.IncidentEpisode,
            });
            // Fetch episode to get workspace channels
            const episode = await IncidentEpisodeService.findOneById({
                id: incidentEpisodeId,
                select: {
                    postUpdatesToWorkspaceChannels: true,
                },
                props: {
                    isRoot: true,
                },
            });
            if (episode) {
                WorkspaceNotificationRuleService.inviteUsersBasedOnRulesAndWorkspaceChannels({
                    notificationRules: notificationRules,
                    projectId: projectId,
                    workspaceChannels: episode.postUpdatesToWorkspaceChannels || [],
                    userIds: [userId],
                }).catch((error) => {
                    logger.error(error);
                });
            }
        }
        return createdItem;
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeFind", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "countBy", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeUpdate", null);
__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=IncidentEpisodeOwnerUserService.js.map