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/IncidentInternalNote";
import IncidentFeedService from "./IncidentFeedService";
import { IncidentFeedEventType } from "../../Models/DatabaseModels/IncidentFeed";
import { Blue500 } from "../../Types/BrandColors";
import { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
import IncidentService from "./IncidentService";
import { applyIncidentRelatedRecordPrivacyFilter } from "../Utils/Incident/IncidentPrivacyFilter";
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 = applyIncidentRelatedRecordPrivacyFilter(findBy.query, findBy.props);
        return { findBy, carryForward: null };
    }
    async countBy(countBy) {
        countBy.query = applyIncidentRelatedRecordPrivacyFilter(countBy.query, countBy.props);
        return super.countBy(countBy);
    }
    async onBeforeUpdate(updateBy) {
        updateBy.query = applyIncidentRelatedRecordPrivacyFilter(updateBy.query, updateBy.props);
        return { updateBy, carryForward: null };
    }
    async onBeforeDelete(deleteBy) {
        deleteBy.query = applyIncidentRelatedRecordPrivacyFilter(deleteBy.query, deleteBy.props);
        return { deleteBy, carryForward: null };
    }
    async addNote(data) {
        const internalNote = new Model();
        internalNote.createdByUserId = data.userId;
        internalNote.incidentId = data.incidentId;
        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: {
                incidentId: data.incidentId,
                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 incidentId = createdItem.incidentId;
        const incidentNumberResult = await IncidentService.getIncidentNumber({
            incidentId: incidentId,
        });
        const incidentNumberDisplay = incidentNumberResult.numberWithPrefix ||
            "#" + incidentNumberResult.number;
        const attachmentsMarkdown = await this.getAttachmentsMarkdown(createdItem.id, "/incident-internal-note/attachment");
        await IncidentFeedService.createIncidentFeedItem({
            incidentId: createdItem.incidentId,
            projectId: createdItem.projectId,
            incidentFeedEventType: IncidentFeedEventType.PrivateNote,
            displayColor: Blue500,
            userId: userId || undefined,
            feedInfoInMarkdown: `📄 posted **private note** for this [Incident ${incidentNumberDisplay}](${(await IncidentService.getIncidentLinkInDashboard(createdItem.projectId, incidentId)).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: {
                    incidentId: true,
                    incident: {
                        projectId: true,
                        incidentNumber: true,
                    },
                    projectId: true,
                    note: true,
                    createdByUserId: true,
                    createdByUser: {
                        _id: true,
                    },
                },
            });
            const userId = onUpdate.updateBy.props.userId;
            for (const updatedItem of updatedItems) {
                const incident = updatedItem.incident;
                const attachmentsMarkdown = await this.getAttachmentsMarkdown(updatedItem.id, "/incident-internal-note/attachment");
                await IncidentFeedService.createIncidentFeedItem({
                    incidentId: updatedItem.incidentId,
                    projectId: updatedItem.projectId,
                    incidentFeedEventType: IncidentFeedEventType.PrivateNote,
                    displayColor: Blue500,
                    userId: userId || undefined,
                    feedInfoInMarkdown: `📄 updated **Private Note** for this [Incident ${incident.incidentNumber}](${(await IncidentService.getIncidentLinkInDashboard(incident.projectId, incident.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=IncidentInternalNoteService.js.map