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/IncidentEpisodeMember";
import { IsBillingEnabled } from "../EnvironmentConfig";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
import IncidentEpisodeFeedService from "./IncidentEpisodeFeedService";
import IncidentFeedService from "./IncidentFeedService";
import { IncidentEpisodeFeedEventType } from "../../Models/DatabaseModels/IncidentEpisodeFeed";
import { IncidentFeedEventType } from "../../Models/DatabaseModels/IncidentFeed";
import { Yellow500, Green500 } from "../../Types/BrandColors";
import OneUptimeDate from "../../Types/Date";
import IncidentService from "./IncidentService";
import IncidentEpisodeService from "./IncidentEpisodeService";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
        if (IsBillingEnabled) {
            this.hardDeleteItemsOlderThanInDays("createdAt", 3 * 365); // 3 years
        }
    }
    async onBeforeCreate(createBy) {
        if (!createBy.data.incidentEpisodeId) {
            throw new BadDataException("incidentEpisodeId is required");
        }
        if (!createBy.data.incidentId) {
            throw new BadDataException("incidentId is required");
        }
        // Check if this incident is already in the episode
        const existingMember = await this.findOneBy({
            query: {
                incidentEpisodeId: createBy.data.incidentEpisodeId,
                incidentId: createBy.data.incidentId,
            },
            props: {
                isRoot: true,
            },
            select: {
                _id: true,
            },
        });
        if (existingMember) {
            throw new BadDataException("Incident 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 incident in the episode (the founder), the
         * "episode created" notification already covers it. Mark the member as
         * "already notified" so the IncidentAdded-to-episode cron skips it. This
         * avoids double-notifying owners when an episode is born with its first
         * incident.
         */
        if (createBy.data.isOwnerNotifiedOfIncidentAdded === undefined) {
            const existingMemberCount = await this.countBy({
                query: {
                    incidentEpisodeId: createBy.data.incidentEpisodeId,
                },
                props: {
                    isRoot: true,
                },
            });
            if (existingMemberCount.toNumber() === 0) {
                createBy.data.isOwnerNotifiedOfIncidentAdded = true;
            }
        }
        return { createBy, carryForward: null };
    }
    async onCreateSuccess(_onCreate, createdItem) {
        if (!createdItem.incidentEpisodeId) {
            throw new BadDataException("incidentEpisodeId is required");
        }
        if (!createdItem.incidentId) {
            throw new BadDataException("incidentId is required");
        }
        if (!createdItem.projectId) {
            throw new BadDataException("projectId is required");
        }
        // Update incident's episode reference
        await IncidentService.updateOneById({
            id: createdItem.incidentId,
            data: {
                incidentEpisodeId: createdItem.incidentEpisodeId,
            },
            props: {
                isRoot: true,
            },
        });
        // Update episode's incidentCount and lastIncidentAddedAt
        try {
            await IncidentEpisodeService.updateIncidentCount(createdItem.incidentEpisodeId);
            await IncidentEpisodeService.updateLastIncidentAddedAt(createdItem.incidentEpisodeId);
        }
        catch (error) {
            logger.error(`Error updating episode counts in IncidentEpisodeMemberService.onCreateSuccess: ${error}`);
        }
        // Get incident details for feed
        const incident = await IncidentService.findOneById({
            id: createdItem.incidentId,
            select: {
                incidentNumber: true,
                incidentNumberWithPrefix: true,
                title: true,
            },
            props: {
                isRoot: true,
            },
        });
        // Get episode details for feed
        const episode = await IncidentEpisodeService.findOneById({
            id: createdItem.incidentEpisodeId,
            select: {
                episodeNumber: true,
                episodeNumberWithPrefix: true,
                title: true,
            },
            props: {
                isRoot: true,
            },
        });
        // Create feed item on episode
        await IncidentEpisodeFeedService.createIncidentEpisodeFeedItem({
            incidentEpisodeId: createdItem.incidentEpisodeId,
            projectId: createdItem.projectId,
            incidentEpisodeFeedEventType: IncidentEpisodeFeedEventType.IncidentAdded,
            displayColor: Yellow500,
            feedInfoInMarkdown: `**Incident ${(incident === null || incident === void 0 ? void 0 : incident.incidentNumberWithPrefix) || "#" + ((incident === null || incident === void 0 ? void 0 : incident.incidentNumber) || "N/A")}** added to episode: ${(incident === null || incident === void 0 ? void 0 : incident.title) || "No title"}`,
            userId: createdItem.addedByUserId || undefined,
            workspaceNotification: {
                sendWorkspaceNotification: true,
                notifyUserId: createdItem.addedByUserId || undefined,
            },
        });
        // Create feed item on incident
        await IncidentFeedService.createIncidentFeedItem({
            incidentId: createdItem.incidentId,
            projectId: createdItem.projectId,
            incidentFeedEventType: IncidentFeedEventType.IncidentUpdated,
            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: {
                incidentEpisodeId: true,
                incidentId: 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.incidentId) {
                    // Clear the episode reference from the incident
                    await IncidentService.updateOneById({
                        id: member.incidentId,
                        data: {
                            incidentEpisodeId: undefined,
                        },
                        props: {
                            isRoot: true,
                        },
                    });
                    // Get incident details for feed
                    const incident = await IncidentService.findOneById({
                        id: member.incidentId,
                        select: {
                            incidentNumber: true,
                            incidentNumberWithPrefix: true,
                            title: true,
                        },
                        props: {
                            isRoot: true,
                        },
                    });
                    // Create feed item for removal
                    if (member.incidentEpisodeId && member.projectId) {
                        // Get episode details for feed
                        const episode = await IncidentEpisodeService.findOneById({
                            id: member.incidentEpisodeId,
                            select: {
                                episodeNumber: true,
                                episodeNumberWithPrefix: true,
                                title: true,
                            },
                            props: {
                                isRoot: true,
                            },
                        });
                        // Create feed item on episode
                        await IncidentEpisodeFeedService.createIncidentEpisodeFeedItem({
                            incidentEpisodeId: member.incidentEpisodeId,
                            projectId: member.projectId,
                            incidentEpisodeFeedEventType: IncidentEpisodeFeedEventType.IncidentRemoved,
                            displayColor: Green500,
                            feedInfoInMarkdown: `**Incident ${(incident === null || incident === void 0 ? void 0 : incident.incidentNumberWithPrefix) || "#" + ((incident === null || incident === void 0 ? void 0 : incident.incidentNumber) || "N/A")}** removed from episode: ${(incident === null || incident === void 0 ? void 0 : incident.title) || "No title"}`,
                            workspaceNotification: {
                                sendWorkspaceNotification: true,
                            },
                        });
                        // Create feed item on incident
                        await IncidentFeedService.createIncidentFeedItem({
                            incidentId: member.incidentId,
                            projectId: member.projectId,
                            incidentFeedEventType: IncidentFeedEventType.IncidentUpdated,
                            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.incidentEpisodeId) {
                    // Update episode's incidentCount
                    await IncidentEpisodeService.updateIncidentCount(member.incidentEpisodeId);
                }
            }
        }
        return onDelete;
    }
    async getIncidentsInEpisode(episodeId) {
        const members = await this.findBy({
            query: {
                incidentEpisodeId: episodeId,
            },
            props: {
                isRoot: true,
            },
            select: {
                incidentId: true,
            },
            limit: 1000,
            skip: 0,
        });
        return members
            .filter((m) => {
            return m.incidentId;
        })
            .map((m) => {
            return m.incidentId;
        });
    }
    async isIncidentInEpisode(incidentId, episodeId) {
        const member = await this.findOneBy({
            query: {
                incidentId: incidentId,
                incidentEpisodeId: 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, "getIncidentsInEpisode", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID,
        ObjectID]),
    __metadata("design:returntype", Promise)
], Service.prototype, "isIncidentInEpisode", null);
export default new Service();
//# sourceMappingURL=IncidentEpisodeMemberService.js.map