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 ObjectID from "../../Types/ObjectID";
import DatabaseService from "./DatabaseService";
import Model from "../../Models/DatabaseModels/AlertEpisodeInternalNote";
import AlertEpisodeFeedService from "./AlertEpisodeFeedService";
import { AlertEpisodeFeedEventType } from "../../Models/DatabaseModels/AlertEpisodeFeed";
import { Blue500 } from "../../Types/BrandColors";
import { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
import AlertEpisodeService from "./AlertEpisodeService";
import { applyAlertEpisodeRelatedRecordPrivacyFilter } from "../Utils/AlertEpisode/AlertEpisodePrivacyFilter";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import File from "../../Models/DatabaseModels/File";
import FileAttachmentMarkdownUtil from "../Utils/FileAttachmentMarkdownUtil";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeFind(findBy) {
        findBy.query = applyAlertEpisodeRelatedRecordPrivacyFilter(findBy.query, findBy.props);
        return { findBy, carryForward: null };
    }
    async countBy(countBy) {
        countBy.query = applyAlertEpisodeRelatedRecordPrivacyFilter(countBy.query, countBy.props);
        return super.countBy(countBy);
    }
    async onBeforeUpdate(updateBy) {
        updateBy.query = applyAlertEpisodeRelatedRecordPrivacyFilter(updateBy.query, updateBy.props);
        return { updateBy, carryForward: null };
    }
    async onBeforeDelete(deleteBy) {
        deleteBy.query = applyAlertEpisodeRelatedRecordPrivacyFilter(deleteBy.query, deleteBy.props);
        return { deleteBy, carryForward: null };
    }
    async addNote(data) {
        const internalNote = new Model();
        internalNote.createdByUserId = data.userId;
        internalNote.alertEpisodeId = data.alertEpisodeId;
        internalNote.projectId = data.projectId;
        internalNote.note = data.note;
        if (data.postedFromSlackMessageId) {
            internalNote.postedFromSlackMessageId = data.postedFromSlackMessageId;
        }
        if (data.attachmentFileIds && data.attachmentFileIds.length > 0) {
            internalNote.attachments = data.attachmentFileIds.map((fileId) => {
                const file = new File();
                file.id = fileId;
                return file;
            });
        }
        return this.create({
            data: internalNote,
            props: {
                isRoot: true,
            },
        });
    }
    async hasNoteFromSlackMessage(data) {
        const existingNote = await this.findOneBy({
            query: {
                alertEpisodeId: data.alertEpisodeId,
                postedFromSlackMessageId: data.postedFromSlackMessageId,
            },
            select: {
                _id: true,
            },
            props: {
                isRoot: true,
            },
        });
        return existingNote !== null;
    }
    async onCreateSuccess(_onCreate, createdItem) {
        var _a;
        const userId = createdItem.createdByUserId || ((_a = createdItem.createdByUser) === null || _a === void 0 ? void 0 : _a.id);
        const alertEpisodeId = createdItem.alertEpisodeId;
        const episodeNumberResult = await AlertEpisodeService.getEpisodeNumber({
            episodeId: alertEpisodeId,
        });
        const episodeNumberDisplay = episodeNumberResult.numberWithPrefix || "#" + episodeNumberResult.number;
        const attachmentsMarkdown = await this.getAttachmentsMarkdown(createdItem.id, "/alert-episode-internal-note/attachment");
        await AlertEpisodeFeedService.createAlertEpisodeFeedItem({
            alertEpisodeId: createdItem.alertEpisodeId,
            projectId: createdItem.projectId,
            alertEpisodeFeedEventType: AlertEpisodeFeedEventType.PrivateNote,
            displayColor: Blue500,
            userId: userId || undefined,
            feedInfoInMarkdown: `📄 posted **private note** for this [Episode ${episodeNumberDisplay}](${(await AlertEpisodeService.getEpisodeLinkInDashboard(createdItem.projectId, alertEpisodeId)).toString()}):

${(createdItem.note || "") + attachmentsMarkdown}
          `,
            workspaceNotification: {
                sendWorkspaceNotification: true,
                notifyUserId: userId || undefined,
            },
        });
        return createdItem;
    }
    async onUpdateSuccess(onUpdate, _updatedItemIds) {
        if (onUpdate.updateBy.data.note) {
            const updatedItems = await this.findBy({
                query: onUpdate.updateBy.query,
                limit: LIMIT_PER_PROJECT,
                skip: 0,
                props: {
                    isRoot: true,
                },
                select: {
                    alertEpisodeId: true,
                    alertEpisode: {
                        projectId: true,
                        episodeNumber: true,
                        episodeNumberWithPrefix: true,
                    },
                    projectId: true,
                    note: true,
                    createdByUserId: true,
                    createdByUser: {
                        _id: true,
                    },
                },
            });
            const userId = onUpdate.updateBy.props.userId;
            for (const updatedItem of updatedItems) {
                const episode = updatedItem.alertEpisode;
                const attachmentsMarkdown = await this.getAttachmentsMarkdown(updatedItem.id, "/alert-episode-internal-note/attachment");
                await AlertEpisodeFeedService.createAlertEpisodeFeedItem({
                    alertEpisodeId: updatedItem.alertEpisodeId,
                    projectId: updatedItem.projectId,
                    alertEpisodeFeedEventType: AlertEpisodeFeedEventType.PrivateNote,
                    displayColor: Blue500,
                    userId: userId || undefined,
                    feedInfoInMarkdown: `📄 updated **Private Note** for this [Episode ${episode.episodeNumberWithPrefix || "#" + episode.episodeNumber}](${(await AlertEpisodeService.getEpisodeLinkInDashboard(episode.projectId, episode.id)).toString()})

${(updatedItem.note || "") + attachmentsMarkdown}
          `,
                    workspaceNotification: {
                        sendWorkspaceNotification: true,
                        notifyUserId: userId || undefined,
                    },
                });
            }
        }
        return onUpdate;
    }
    async getAttachmentsMarkdown(modelId, attachmentApiPath) {
        if (!modelId) {
            return "";
        }
        const noteWithAttachments = await this.findOneById({
            id: modelId,
            select: {
                attachments: {
                    _id: true,
                },
            },
            props: {
                isRoot: true,
            },
        });
        if (!noteWithAttachments || !noteWithAttachments.attachments) {
            return "";
        }
        const attachmentIds = noteWithAttachments.attachments
            .map((file) => {
            if (file.id) {
                return file.id;
            }
            if (file._id) {
                return new ObjectID(file._id);
            }
            return null;
        })
            .filter((id) => {
            return Boolean(id);
        });
        if (!attachmentIds.length) {
            return "";
        }
        return await FileAttachmentMarkdownUtil.buildAttachmentMarkdown({
            modelId,
            attachmentIds,
            attachmentApiPath,
        });
    }
}
__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]),
    __metadata("design:returntype", Promise)
], Service.prototype, "addNote", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "hasNoteFromSlackMessage", 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, Array]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onUpdateSuccess", null);
export default new Service();
//# sourceMappingURL=AlertEpisodeInternalNoteService.js.map