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 BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import Model from "../../Models/DatabaseModels/AlertEpisodeMember";
import { IsBillingEnabled } from "../EnvironmentConfig";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
import AlertEpisodeFeedService from "./AlertEpisodeFeedService";
import AlertFeedService from "./AlertFeedService";
import { AlertEpisodeFeedEventType } from "../../Models/DatabaseModels/AlertEpisodeFeed";
import { AlertFeedEventType } from "../../Models/DatabaseModels/AlertFeed";
import { Yellow500, Green500 } from "../../Types/BrandColors";
import OneUptimeDate from "../../Types/Date";
import AlertService from "./AlertService";
import AlertEpisodeService from "./AlertEpisodeService";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
        if (IsBillingEnabled) {
            this.hardDeleteItemsOlderThanInDays("createdAt", 3 * 365); // 3 years
        }
    }
    async onBeforeCreate(createBy) {
        if (!createBy.data.alertEpisodeId) {
            throw new BadDataException("alertEpisodeId is required");
        }
        if (!createBy.data.alertId) {
            throw new BadDataException("alertId is required");
        }
        // Check if this alert is already in the episode
        const existingMember = await this.findOneBy({
            query: {
                alertEpisodeId: createBy.data.alertEpisodeId,
                alertId: createBy.data.alertId,
            },
            props: {
                isRoot: true,
            },
            select: {
                _id: true,
            },
        });
        if (existingMember) {
            throw new BadDataException("Alert is already a member of this episode");
        }
        // Set addedAt if not provided
        if (!createBy.data.addedAt) {
            createBy.data.addedAt = OneUptimeDate.getCurrentDate();
        }
        /*
         * If this is the very first alert in the episode (the founder), the
         * "episode created" notification already covers it. Mark the member as
         * "already notified" so the AlertAdded-to-episode cron skips it. This
         * avoids double-notifying owners when an episode is born with its first
         * alert.
         */
        if (createBy.data.isOwnerNotifiedOfAlertAdded === undefined) {
            const existingMemberCount = await this.countBy({
                query: {
                    alertEpisodeId: createBy.data.alertEpisodeId,
                },
                props: {
                    isRoot: true,
                },
            });
            if (existingMemberCount.toNumber() === 0) {
                createBy.data.isOwnerNotifiedOfAlertAdded = true;
            }
        }
        return { createBy, carryForward: null };
    }
    async onCreateSuccess(_onCreate, createdItem) {
        if (!createdItem.alertEpisodeId) {
            throw new BadDataException("alertEpisodeId is required");
        }
        if (!createdItem.alertId) {
            throw new BadDataException("alertId is required");
        }
        if (!createdItem.projectId) {
            throw new BadDataException("projectId is required");
        }
        // Update alert's episode reference
        await AlertService.updateOneById({
            id: createdItem.alertId,
            data: {
                alertEpisodeId: createdItem.alertEpisodeId,
            },
            props: {
                isRoot: true,
            },
        });
        // Update episode's alertCount and lastAlertAddedAt
        try {
            await AlertEpisodeService.updateAlertCount(createdItem.alertEpisodeId);
            await AlertEpisodeService.updateLastAlertAddedAt(createdItem.alertEpisodeId);
        }
        catch (error) {
            logger.error(`Error updating episode counts in AlertEpisodeMemberService.onCreateSuccess: ${error}`);
        }
        // Get alert details for feed
        const alert = await AlertService.findOneById({
            id: createdItem.alertId,
            select: {
                alertNumber: true,
                alertNumberWithPrefix: true,
                title: true,
            },
            props: {
                isRoot: true,
            },
        });
        // Get episode details for feed
        const episode = await AlertEpisodeService.findOneById({
            id: createdItem.alertEpisodeId,
            select: {
                episodeNumber: true,
                episodeNumberWithPrefix: true,
                title: true,
            },
            props: {
                isRoot: true,
            },
        });
        // Create feed item on episode
        await AlertEpisodeFeedService.createAlertEpisodeFeedItem({
            alertEpisodeId: createdItem.alertEpisodeId,
            projectId: createdItem.projectId,
            alertEpisodeFeedEventType: AlertEpisodeFeedEventType.AlertAdded,
            displayColor: Yellow500,
            feedInfoInMarkdown: `**Alert ${(alert === null || alert === void 0 ? void 0 : alert.alertNumberWithPrefix) || "#" + ((alert === null || alert === void 0 ? void 0 : alert.alertNumber) || "N/A")}** added to episode: ${(alert === null || alert === void 0 ? void 0 : alert.title) || "No title"}`,
            userId: createdItem.addedByUserId || undefined,
            workspaceNotification: {
                sendWorkspaceNotification: true,
                notifyUserId: createdItem.addedByUserId || undefined,
            },
        });
        // Create feed item on alert
        await AlertFeedService.createAlertFeedItem({
            alertId: createdItem.alertId,
            projectId: createdItem.projectId,
            alertFeedEventType: AlertFeedEventType.AddedToEpisode,
            displayColor: Yellow500,
            feedInfoInMarkdown: `Added to **Episode ${(episode === null || episode === void 0 ? void 0 : episode.episodeNumberWithPrefix) || "#" + ((episode === null || episode === void 0 ? void 0 : episode.episodeNumber) || "N/A")}**: ${(episode === null || episode === void 0 ? void 0 : episode.title) || "No title"}`,
            userId: createdItem.addedByUserId || undefined,
        });
        return createdItem;
    }
    async onBeforeDelete(deleteBy) {
        // Get the member records before deletion
        const membersToDelete = await this.findBy({
            query: deleteBy.query,
            props: {
                isRoot: true,
            },
            select: {
                alertEpisodeId: true,
                alertId: true,
                projectId: true,
            },
            limit: 100,
            skip: 0,
        });
        return {
            deleteBy,
            carryForward: membersToDelete,
        };
    }
    async onDeleteSuccess(onDelete, _itemIdsBeforeDelete) {
        const membersDeleted = onDelete.carryForward;
        if (membersDeleted && membersDeleted.length > 0) {
            for (const member of membersDeleted) {
                if (member.alertId) {
                    // Clear the episode reference from the alert
                    await AlertService.updateOneById({
                        id: member.alertId,
                        data: {
                            alertEpisodeId: undefined,
                        },
                        props: {
                            isRoot: true,
                        },
                    });
                    // Get alert details for feed
                    const alert = await AlertService.findOneById({
                        id: member.alertId,
                        select: {
                            alertNumber: true,
                            title: true,
                        },
                        props: {
                            isRoot: true,
                        },
                    });
                    // Create feed item for removal
                    if (member.alertEpisodeId && member.projectId) {
                        // Get episode details for feed
                        const episode = await AlertEpisodeService.findOneById({
                            id: member.alertEpisodeId,
                            select: {
                                episodeNumber: true,
                                episodeNumberWithPrefix: true,
                                title: true,
                            },
                            props: {
                                isRoot: true,
                            },
                        });
                        // Create feed item on episode
                        await AlertEpisodeFeedService.createAlertEpisodeFeedItem({
                            alertEpisodeId: member.alertEpisodeId,
                            projectId: member.projectId,
                            alertEpisodeFeedEventType: AlertEpisodeFeedEventType.AlertRemoved,
                            displayColor: Green500,
                            feedInfoInMarkdown: `**Alert #${(alert === null || alert === void 0 ? void 0 : alert.alertNumber) || "N/A"}** removed from episode: ${(alert === null || alert === void 0 ? void 0 : alert.title) || "No title"}`,
                            workspaceNotification: {
                                sendWorkspaceNotification: true,
                            },
                        });
                        // Create feed item on alert
                        await AlertFeedService.createAlertFeedItem({
                            alertId: member.alertId,
                            projectId: member.projectId,
                            alertFeedEventType: AlertFeedEventType.RemovedFromEpisode,
                            displayColor: Green500,
                            feedInfoInMarkdown: `Removed from **Episode ${(episode === null || episode === void 0 ? void 0 : episode.episodeNumberWithPrefix) || "#" + ((episode === null || episode === void 0 ? void 0 : episode.episodeNumber) || "N/A")}**: ${(episode === null || episode === void 0 ? void 0 : episode.title) || "No title"}`,
                        });
                    }
                }
                if (member.alertEpisodeId) {
                    // Update episode's alertCount
                    await AlertEpisodeService.updateAlertCount(member.alertEpisodeId);
                }
            }
        }
        return onDelete;
    }
    async getAlertsInEpisode(episodeId) {
        const members = await this.findBy({
            query: {
                alertEpisodeId: episodeId,
            },
            props: {
                isRoot: true,
            },
            select: {
                alertId: true,
            },
            limit: 1000,
            skip: 0,
        });
        return members
            .filter((m) => {
            return m.alertId;
        })
            .map((m) => {
            return m.alertId;
        });
    }
    async isAlertInEpisode(alertId, episodeId) {
        const member = await this.findOneBy({
            query: {
                alertId: alertId,
                alertEpisodeId: episodeId,
            },
            props: {
                isRoot: true,
            },
            select: {
                _id: true,
            },
        });
        return member !== 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, "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", [ObjectID]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getAlertsInEpisode", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID,
        ObjectID]),
    __metadata("design:returntype", Promise)
], Service.prototype, "isAlertInEpisode", null);
export default new Service();
//# sourceMappingURL=AlertEpisodeMemberService.js.map