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 OneUptimeDate from "../../Types/Date";
import Model from "../../Models/DatabaseModels/ScheduledMaintenancePublicNote";
import ScheduledMaintenanceFeedService from "./ScheduledMaintenanceFeedService";
import ObjectID from "../../Types/ObjectID";
import { ScheduledMaintenanceFeedEventType } from "../../Models/DatabaseModels/ScheduledMaintenanceFeed";
import { Blue500, Indigo500 } from "../../Types/BrandColors";
import { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
import ScheduledMaintenanceService from "./ScheduledMaintenanceService";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import StatusPageSubscriberNotificationStatus from "../../Types/StatusPage/StatusPageSubscriberNotificationStatus";
import File from "../../Models/DatabaseModels/File";
import FileAttachmentMarkdownUtil from "../Utils/FileAttachmentMarkdownUtil";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        if (!createBy.data.postedAt) {
            createBy.data.postedAt = OneUptimeDate.getCurrentDate();
        }
        // Set notification status based on shouldStatusPageSubscribersBeNotifiedOnNoteCreated
        if (createBy.data.shouldStatusPageSubscribersBeNotifiedOnNoteCreated === false) {
            createBy.data.subscriberNotificationStatusOnNoteCreated =
                StatusPageSubscriberNotificationStatus.Skipped;
            createBy.data.subscriberNotificationStatusMessage =
                "Notifications skipped as subscribers are not to be notified for this scheduled maintenance note.";
        }
        else if (createBy.data.shouldStatusPageSubscribersBeNotifiedOnNoteCreated === true) {
            createBy.data.subscriberNotificationStatusOnNoteCreated =
                StatusPageSubscriberNotificationStatus.Pending;
        }
        return {
            createBy: createBy,
            carryForward: null,
        };
    }
    async onCreateSuccess(_onCreate, createdItem) {
        var _a;
        const userId = createdItem.createdByUserId || ((_a = createdItem.createdByUser) === null || _a === void 0 ? void 0 : _a.id);
        const scheduledMaintenanceId = createdItem.scheduledMaintenanceId;
        const projectId = createdItem.projectId;
        const scheduledMaintenanceNumberResult = await ScheduledMaintenanceService.getScheduledMaintenanceNumber({
            scheduledMaintenanceId: scheduledMaintenanceId,
        });
        const attachmentsMarkdown = await this.getAttachmentsMarkdown(createdItem.id, "/scheduled-maintenance-public-note/attachment");
        await ScheduledMaintenanceFeedService.createScheduledMaintenanceFeedItem({
            scheduledMaintenanceId: createdItem.scheduledMaintenanceId,
            projectId: createdItem.projectId,
            scheduledMaintenanceFeedEventType: ScheduledMaintenanceFeedEventType.PublicNote,
            displayColor: Indigo500,
            userId: userId || undefined,
            feedInfoInMarkdown: `📄 posted **public note** for this [Scheduled Maintenance ${scheduledMaintenanceNumberResult.numberWithPrefix || "#" + scheduledMaintenanceNumberResult.number}](${(await ScheduledMaintenanceService.getScheduledMaintenanceLinkInDashboard(projectId, scheduledMaintenanceId)).toString()}) on status page:
    
${(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: {
                    scheduledMaintenanceId: true,
                    scheduledMaintenance: {
                        _id: true,
                        scheduledMaintenanceNumber: true,
                        scheduledMaintenanceNumberWithPrefix: true,
                        projectId: true,
                    },
                    projectId: true,
                    note: true,
                    createdByUserId: true,
                    createdByUser: {
                        _id: true,
                    },
                },
            });
            const userId = onUpdate.updateBy.props.userId;
            for (const updatedItem of updatedItems) {
                const scheduledMaintenance = updatedItem.scheduledMaintenance;
                const attachmentsMarkdown = await this.getAttachmentsMarkdown(updatedItem.id, "/scheduled-maintenance-public-note/attachment");
                await ScheduledMaintenanceFeedService.createScheduledMaintenanceFeedItem({
                    scheduledMaintenanceId: updatedItem.scheduledMaintenanceId,
                    projectId: updatedItem.projectId,
                    scheduledMaintenanceFeedEventType: ScheduledMaintenanceFeedEventType.PrivateNote,
                    displayColor: Blue500,
                    userId: userId || undefined,
                    feedInfoInMarkdown: `📄 updated **Public Note** for this [Scheduled Maintenance ${scheduledMaintenance.scheduledMaintenanceNumberWithPrefix || "#" + scheduledMaintenance.scheduledMaintenanceNumber}](${(await ScheduledMaintenanceService.getScheduledMaintenanceLinkInDashboard(scheduledMaintenance.projectId, scheduledMaintenance.id)).toString()})
        
${(updatedItem.note || "") + attachmentsMarkdown}
                  `,
                    workspaceNotification: {
                        sendWorkspaceNotification: true,
                        notifyUserId: userId || undefined,
                    },
                });
            }
        }
        return onUpdate;
    }
    async addNote(data) {
        const publicNote = new Model();
        publicNote.createdByUserId = data.userId;
        publicNote.scheduledMaintenanceId = data.scheduledMaintenanceId;
        publicNote.projectId = data.projectId;
        publicNote.note = data.note;
        publicNote.postedAt = OneUptimeDate.getCurrentDate();
        if (data.postedFromSlackMessageId) {
            publicNote.postedFromSlackMessageId = data.postedFromSlackMessageId;
        }
        if (data.attachmentFileIds && data.attachmentFileIds.length > 0) {
            publicNote.attachments = data.attachmentFileIds.map((fileId) => {
                const file = new File();
                file.id = fileId;
                return file;
            });
        }
        return this.create({
            data: publicNote,
            props: {
                isRoot: true,
            },
        });
    }
    async hasNoteFromSlackMessage(data) {
        const existingNote = await this.findOneBy({
            query: {
                scheduledMaintenanceId: data.scheduledMaintenanceId,
                postedFromSlackMessageId: data.postedFromSlackMessageId,
            },
            select: {
                _id: true,
            },
            props: {
                isRoot: true,
            },
        });
        return existingNote !== null;
    }
    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, "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, Array]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onUpdateSuccess", 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);
export default new Service();
//# sourceMappingURL=ScheduledMaintenancePublicNoteService.js.map