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/IncidentMember";
import IncidentFeedService from "./IncidentFeedService";
import { IncidentFeedEventType } from "../../Models/DatabaseModels/IncidentFeed";
import { Gray500, Red500 } from "../../Types/BrandColors";
import UserService from "./UserService";
import IncidentService from "./IncidentService";
import WorkspaceNotificationRuleService from "./WorkspaceNotificationRuleService";
import NotificationRuleEventType from "../../Types/Workspace/NotificationRules/EventType";
import logger from "../Utils/Logger";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import IncidentRoleService from "./IncidentRoleService";
import BadDataException from "../../Types/Exception/BadDataException";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        if (!createBy.data.incidentId) {
            throw new BadDataException("incidentId is required");
        }
        if (!createBy.data.userId) {
            throw new BadDataException("userId is required");
        }
        if (!createBy.data.incidentRoleId) {
            throw new BadDataException("incidentRoleId is required");
        }
        // Check if this user is already assigned to this role for this incident
        const existingMember = await this.findOneBy({
            query: {
                incidentId: createBy.data.incidentId,
                userId: createBy.data.userId,
                incidentRoleId: createBy.data.incidentRoleId,
            },
            props: {
                isRoot: true,
            },
            select: {
                _id: true,
            },
        });
        if (existingMember) {
            throw new BadDataException("This user is already assigned to this role for this incident");
        }
        return { createBy, carryForward: null };
    }
    async onBeforeDelete(deleteBy) {
        const itemsToDelete = await this.findBy({
            query: deleteBy.query,
            limit: deleteBy.limit,
            skip: deleteBy.skip,
            props: {
                isRoot: true,
            },
            select: {
                incidentId: true,
                projectId: true,
                userId: true,
                incidentRoleId: 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 incidentId = item.incidentId;
            const projectId = item.projectId;
            const userId = item.userId;
            const incidentRoleId = item.incidentRoleId;
            if (incidentId && userId && projectId) {
                const user = await UserService.findOneById({
                    id: userId,
                    select: {
                        name: true,
                        email: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                let roleName = "Member";
                if (incidentRoleId) {
                    const role = await IncidentRoleService.findOneById({
                        id: incidentRoleId,
                        select: {
                            name: true,
                        },
                        props: {
                            isRoot: true,
                        },
                    });
                    if (role && role.name) {
                        roleName = role.name;
                    }
                }
                const incidentNumberResult = await IncidentService.getIncidentNumber({
                    incidentId: incidentId,
                });
                const incidentNumberDisplay = incidentNumberResult.numberWithPrefix ||
                    "#" + incidentNumberResult.number;
                if (user && user.name) {
                    await IncidentFeedService.createIncidentFeedItem({
                        incidentId: incidentId,
                        projectId: projectId,
                        incidentFeedEventType: IncidentFeedEventType.IncidentMemberRemoved,
                        displayColor: Red500,
                        feedInfoInMarkdown: `👤 Removed **${user.name.toString()}** (${(_b = user.email) === null || _b === void 0 ? void 0 : _b.toString()}) as **${roleName}** from [Incident ${incidentNumberDisplay}](${(await IncidentService.getIncidentLinkInDashboard(projectId, incidentId)).toString()}).`,
                        userId: deleteByUserId || undefined,
                        workspaceNotification: {
                            sendWorkspaceNotification: true,
                            notifyUserId: userId || undefined,
                        },
                    });
                }
            }
        }
        return onDelete;
    }
    async onCreateSuccess(onCreate, createdItem) {
        const incidentId = createdItem.incidentId;
        const projectId = createdItem.projectId;
        const userId = createdItem.userId;
        const incidentRoleId = createdItem.incidentRoleId;
        const createdByUserId = createdItem.createdByUserId || onCreate.createBy.props.userId;
        if (incidentId && userId && projectId) {
            let roleName = "Member";
            if (incidentRoleId) {
                const role = await IncidentRoleService.findOneById({
                    id: incidentRoleId,
                    select: {
                        name: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                if (role && role.name) {
                    roleName = role.name;
                }
            }
            const incidentNumberResult = await IncidentService.getIncidentNumber({
                incidentId: incidentId,
            });
            const incidentNumberDisplay = incidentNumberResult.numberWithPrefix ||
                "#" + incidentNumberResult.number;
            if (userId) {
                await IncidentFeedService.createIncidentFeedItem({
                    incidentId: incidentId,
                    projectId: projectId,
                    incidentFeedEventType: IncidentFeedEventType.IncidentMemberAdded,
                    displayColor: Gray500,
                    feedInfoInMarkdown: `👤 Added **${await UserService.getUserMarkdownString({
                        userId: userId,
                        projectId: projectId,
                    })}** as **${roleName}** to [Incident ${incidentNumberDisplay}](${(await IncidentService.getIncidentLinkInDashboard(projectId, incidentId)).toString()}).`,
                    userId: createdByUserId || undefined,
                    workspaceNotification: {
                        sendWorkspaceNotification: true,
                        notifyUserId: userId || undefined,
                    },
                });
            }
        }
        // get notification rule where inviteOwners is true.
        const notificationRules = await WorkspaceNotificationRuleService.getNotificationRulesWhereInviteOwnersIsTrue({
            projectId: projectId,
            notificationFor: {
                incidentId: incidentId,
            },
            notificationRuleEventType: NotificationRuleEventType.Incident,
        });
        WorkspaceNotificationRuleService.inviteUsersBasedOnRulesAndWorkspaceChannels({
            notificationRules: notificationRules,
            projectId: projectId,
            workspaceChannels: await IncidentService.getWorkspaceChannelForIncident({
                incidentId: incidentId,
            }),
            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, "onBeforeCreate", 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=IncidentMemberService.js.map