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 { Blue500 } from "../../Types/BrandColors";
import OneUptimeDate from "../../Types/Date";
import BadDataException from "../../Types/Exception/BadDataException";
import { IsBillingEnabled } from "../EnvironmentConfig";
import logger from "../Utils/Logger";
import DatabaseService from "./DatabaseService";
import Model from "../../Models/DatabaseModels/AlertEpisodeFeed";
import WorkspaceNotificationRuleService from "./WorkspaceNotificationRuleService";
import { applyAlertEpisodeRelatedRecordPrivacyFilter } from "../Utils/AlertEpisode/AlertEpisodePrivacyFilter";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
        if (IsBillingEnabled) {
            this.hardDeleteItemsOlderThanInDays("createdAt", 3 * 365); // 3 years
        }
    }
    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 createAlertEpisodeFeedItem(data) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        try {
            if (!data.alertEpisodeId) {
                throw new BadDataException("Alert Episode ID is required");
            }
            if (!data.feedInfoInMarkdown) {
                throw new BadDataException("Log in markdown is required");
            }
            if (!data.alertEpisodeFeedEventType) {
                throw new BadDataException("Alert episode log event is required");
            }
            if (!data.projectId) {
                throw new BadDataException("Project ID is required");
            }
            const alertEpisodeFeed = new Model();
            if (!data.displayColor) {
                data.displayColor = Blue500;
            }
            if (data.userId) {
                alertEpisodeFeed.userId = data.userId;
            }
            alertEpisodeFeed.displayColor = data.displayColor;
            alertEpisodeFeed.alertEpisodeId = data.alertEpisodeId;
            alertEpisodeFeed.feedInfoInMarkdown = data.feedInfoInMarkdown;
            alertEpisodeFeed.alertEpisodeFeedEventType =
                data.alertEpisodeFeedEventType;
            alertEpisodeFeed.projectId = data.projectId;
            if (!data.postedAt) {
                alertEpisodeFeed.postedAt = OneUptimeDate.getCurrentDate();
            }
            else {
                alertEpisodeFeed.postedAt = data.postedAt;
            }
            if (data.moreInformationInMarkdown) {
                alertEpisodeFeed.moreInformationInMarkdown =
                    data.moreInformationInMarkdown;
            }
            await this.create({
                data: alertEpisodeFeed,
                props: {
                    isRoot: true,
                },
            });
            try {
                if (data.workspaceNotification &&
                    ((_a = data.workspaceNotification) === null || _a === void 0 ? void 0 : _a.sendWorkspaceNotification)) {
                    await this.sendWorkspaceNotification({
                        projectId: data.projectId,
                        alertEpisodeId: data.alertEpisodeId,
                        feedInfoInMarkdown: data.feedInfoInMarkdown,
                        workspaceNotification: data.workspaceNotification,
                    });
                }
            }
            catch (e) {
                logger.error("Error in sending notification to slack and teams", {
                    projectId: (_b = data.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
                    alertEpisodeId: (_c = data.alertEpisodeId) === null || _c === void 0 ? void 0 : _c.toString(),
                });
                logger.error(e, {
                    projectId: (_d = data.projectId) === null || _d === void 0 ? void 0 : _d.toString(),
                    alertEpisodeId: (_e = data.alertEpisodeId) === null || _e === void 0 ? void 0 : _e.toString(),
                });
            }
        }
        catch (error) {
            logger.error("AlertEpisodeFeedService.createAlertEpisodeFeedItem", {
                projectId: (_f = data.projectId) === null || _f === void 0 ? void 0 : _f.toString(),
                alertEpisodeId: (_g = data.alertEpisodeId) === null || _g === void 0 ? void 0 : _g.toString(),
            });
            logger.error(error, {
                projectId: (_h = data.projectId) === null || _h === void 0 ? void 0 : _h.toString(),
                alertEpisodeId: (_j = data.alertEpisodeId) === null || _j === void 0 ? void 0 : _j.toString(),
            });
            // we dont want to throw the error here, as this is a non-critical operation
        }
    }
    async sendWorkspaceNotification(data) {
        return await WorkspaceNotificationRuleService.sendWorkspaceMarkdownNotification({
            projectId: data.projectId,
            notificationFor: {
                alertEpisodeId: data.alertEpisodeId,
            },
            feedInfoInMarkdown: data.feedInfoInMarkdown,
            workspaceNotification: data.workspaceNotification,
        });
    }
}
__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, "createAlertEpisodeFeedItem", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "sendWorkspaceNotification", null);
export default new Service();
//# sourceMappingURL=AlertEpisodeFeedService.js.map