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 { PlanType } from "../../Types/Billing/SubscriptionPlan";
import DatabaseConfig from "../DatabaseConfig";
import { AllowedSubscribersCountInFreePlan, IsBillingEnabled, } from "../EnvironmentConfig";
import ProjectSMTPConfigService from "../Services/ProjectSmtpConfigService";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import QueryHelper from "../Types/Database/QueryHelper";
import logger from "../Utils/Logger";
import DatabaseService from "./DatabaseService";
import MailService from "./MailService";
import ProjectCallSMSConfigService from "./ProjectCallSMSConfigService";
import ProjectService from "./ProjectService";
import SmsService from "./SmsService";
import StatusPageService from "./StatusPageService";
import { StatusPageApiRoute } from "../../ServiceRoute";
import URL from "../../Types/API/URL";
import LIMIT_MAX, { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
import EmailTemplateType from "../../Types/Email/EmailTemplateType";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import Model from "../../Models/DatabaseModels/StatusPageSubscriber";
import StatusPageEventType from "../../Types/StatusPage/StatusPageEventType";
import StatusPageSubscriberNotificationEventType from "../../Types/StatusPage/StatusPageSubscriberNotificationEventType";
import StatusPageSubscriberNotificationMethod from "../../Types/StatusPage/StatusPageSubscriberNotificationMethod";
import NumberUtil from "../../Utils/Number";
import SlackUtil from "../Utils/Workspace/Slack/Slack";
import MicrosoftTeamsUtil from "../Utils/Workspace/MicrosoftTeams/MicrosoftTeams";
import StatusPageSubscriberWebhookUtil from "../Utils/StatusPageSubscriberWebhook";
import StatusPageSubscriberNotificationTemplateService, { Service as StatusPageSubscriberNotificationTemplateServiceClass, } from "./StatusPageSubscriberNotificationTemplateService";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(data) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37;
        logger.debug("onBeforeCreate called with data:", {
            projectId: (_a = data.data.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
            statusPageId: (_b = data.data.statusPageId) === null || _b === void 0 ? void 0 : _b.toString(),
        });
        logger.debug(data, {
            projectId: (_c = data.data.projectId) === null || _c === void 0 ? void 0 : _c.toString(),
            statusPageId: (_d = data.data.statusPageId) === null || _d === void 0 ? void 0 : _d.toString(),
        });
        if (!data.data.statusPageId) {
            logger.debug("Status Page ID is missing.", {
                projectId: (_e = data.data.projectId) === null || _e === void 0 ? void 0 : _e.toString(),
            });
            throw new BadDataException("Status Page ID is required.");
        }
        if (!data.data.projectId) {
            logger.debug("Project ID is missing.", {
                statusPageId: (_f = data.data.statusPageId) === null || _f === void 0 ? void 0 : _f.toString(),
            });
            throw new BadDataException("Project ID is required.");
        }
        const projectId = data.data.projectId;
        logger.debug(`Project ID: ${projectId}`, {
            projectId: (_g = data.data.projectId) === null || _g === void 0 ? void 0 : _g.toString(),
            statusPageId: (_h = data.data.statusPageId) === null || _h === void 0 ? void 0 : _h.toString(),
        });
        // if the project is on the free plan, then only allow 1 status page.
        if (IsBillingEnabled) {
            logger.debug("Billing is enabled.", {
                projectId: (_j = data.data.projectId) === null || _j === void 0 ? void 0 : _j.toString(),
                statusPageId: (_k = data.data.statusPageId) === null || _k === void 0 ? void 0 : _k.toString(),
            });
            const currentPlan = await ProjectService.getCurrentPlan(projectId);
            logger.debug(`Current Plan: ${JSON.stringify(currentPlan)}`, {
                projectId: (_l = data.data.projectId) === null || _l === void 0 ? void 0 : _l.toString(),
                statusPageId: (_m = data.data.statusPageId) === null || _m === void 0 ? void 0 : _m.toString(),
            });
            if (currentPlan.isSubscriptionUnpaid) {
                logger.debug("Subscription is unpaid.", {
                    projectId: (_o = data.data.projectId) === null || _o === void 0 ? void 0 : _o.toString(),
                    statusPageId: (_p = data.data.statusPageId) === null || _p === void 0 ? void 0 : _p.toString(),
                });
                throw new BadDataException("Your subscription is unpaid. Please update your payment method and to add subscribers.");
            }
            if (currentPlan.plan === PlanType.Free) {
                logger.debug("Current plan is Free.", {
                    projectId: (_q = data.data.projectId) === null || _q === void 0 ? void 0 : _q.toString(),
                    statusPageId: (_r = data.data.statusPageId) === null || _r === void 0 ? void 0 : _r.toString(),
                });
                const subscribersCount = await this.countBy({
                    query: {
                        projectId: projectId,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                logger.debug(`Subscribers Count: ${subscribersCount.toNumber()}`, {
                    projectId: (_s = data.data.projectId) === null || _s === void 0 ? void 0 : _s.toString(),
                    statusPageId: (_t = data.data.statusPageId) === null || _t === void 0 ? void 0 : _t.toString(),
                });
                if (subscribersCount.toNumber() >= AllowedSubscribersCountInFreePlan) {
                    logger.debug("Reached maximum allowed subscriber limit for the free plan.", {
                        projectId: (_u = data.data.projectId) === null || _u === void 0 ? void 0 : _u.toString(),
                        statusPageId: (_v = data.data.statusPageId) === null || _v === void 0 ? void 0 : _v.toString(),
                    });
                    throw new BadDataException(`You have reached the maximum allowed subscriber limit for the free plan. Please upgrade your plan to add more subscribers.`);
                }
            }
        }
        let subscriber = null;
        if (data.data.subscriberEmail) {
            logger.debug(`Subscriber Email: ${data.data.subscriberEmail}`, {
                projectId: (_w = data.data.projectId) === null || _w === void 0 ? void 0 : _w.toString(),
                statusPageId: (_x = data.data.statusPageId) === null || _x === void 0 ? void 0 : _x.toString(),
            });
            subscriber = await this.findOneBy({
                query: {
                    statusPageId: data.data.statusPageId,
                    subscriberEmail: data.data.subscriberEmail,
                },
                select: {
                    _id: true,
                    isUnsubscribed: true,
                },
                props: {
                    isRoot: true,
                    ignoreHooks: true,
                },
            });
            logger.debug(`Found Subscriber by Email: ${JSON.stringify(subscriber)}`, {
                projectId: (_y = data.data.projectId) === null || _y === void 0 ? void 0 : _y.toString(),
                statusPageId: (_z = data.data.statusPageId) === null || _z === void 0 ? void 0 : _z.toString(),
            });
        }
        if (data.data.subscriberPhone) {
            logger.debug(`Subscriber Phone: ${data.data.subscriberPhone}`, {
                projectId: (_0 = data.data.projectId) === null || _0 === void 0 ? void 0 : _0.toString(),
                statusPageId: (_1 = data.data.statusPageId) === null || _1 === void 0 ? void 0 : _1.toString(),
            });
            // check if this project has SMS enabled.
            const isSMSEnabled = await ProjectService.isSMSNotificationsEnabled(projectId);
            logger.debug(`Is SMS Enabled: ${isSMSEnabled}`, {
                projectId: (_2 = data.data.projectId) === null || _2 === void 0 ? void 0 : _2.toString(),
                statusPageId: (_3 = data.data.statusPageId) === null || _3 === void 0 ? void 0 : _3.toString(),
            });
            if (!isSMSEnabled) {
                logger.debug("SMS notifications are not enabled for this project.", {
                    projectId: (_4 = data.data.projectId) === null || _4 === void 0 ? void 0 : _4.toString(),
                    statusPageId: (_5 = data.data.statusPageId) === null || _5 === void 0 ? void 0 : _5.toString(),
                });
                throw new BadDataException("SMS notifications are not enabled for this project. Please enable SMS notifications in the Project Settings > Notifications Settings.");
            }
            subscriber = await this.findOneBy({
                query: {
                    statusPageId: data.data.statusPageId,
                    subscriberPhone: data.data.subscriberPhone,
                },
                select: {
                    _id: true,
                    isUnsubscribed: true,
                },
                props: {
                    isRoot: true,
                    ignoreHooks: true,
                },
            });
            logger.debug(`Found Subscriber by Phone: ${JSON.stringify(subscriber)}`, {
                projectId: (_6 = data.data.projectId) === null || _6 === void 0 ? void 0 : _6.toString(),
                statusPageId: (_7 = data.data.statusPageId) === null || _7 === void 0 ? void 0 : _7.toString(),
            });
        }
        if (subscriber && !subscriber.isUnsubscribed) {
            logger.debug("Subscriber is already subscribed and not unsubscribed.", {
                projectId: (_8 = data.data.projectId) === null || _8 === void 0 ? void 0 : _8.toString(),
                statusPageId: (_9 = data.data.statusPageId) === null || _9 === void 0 ? void 0 : _9.toString(),
            });
            throw new BadDataException("You are already subscribed to this status page.");
        }
        // if the user is unsubscribed, delete this record and it'll create a new one.
        if (subscriber) {
            logger.debug("Subscriber is unsubscribed. Deleting old record.", {
                projectId: (_10 = data.data.projectId) === null || _10 === void 0 ? void 0 : _10.toString(),
                statusPageId: (_11 = data.data.statusPageId) === null || _11 === void 0 ? void 0 : _11.toString(),
            });
            await this.deleteOneBy({
                query: {
                    _id: subscriber === null || subscriber === void 0 ? void 0 : subscriber._id,
                },
                props: {
                    ignoreHooks: true,
                    isRoot: true,
                },
            });
        }
        const statuspages = await this.getStatusPagesToSendNotification([data.data.statusPageId]);
        logger.debug(`Status Pages: ${JSON.stringify(statuspages)}`, {
            projectId: (_12 = data.data.projectId) === null || _12 === void 0 ? void 0 : _12.toString(),
            statusPageId: (_13 = data.data.statusPageId) === null || _13 === void 0 ? void 0 : _13.toString(),
        });
        const statuspage = statuspages.find((statuspage) => {
            var _a, _b;
            return (((_a = statuspage._id) === null || _a === void 0 ? void 0 : _a.toString()) === ((_b = data.data.statusPageId) === null || _b === void 0 ? void 0 : _b.toString()));
        });
        if (!statuspage || !statuspage.projectId) {
            logger.debug("Status Page not found or Project ID is missing.", {
                projectId: (_14 = data.data.projectId) === null || _14 === void 0 ? void 0 : _14.toString(),
                statusPageId: (_15 = data.data.statusPageId) === null || _15 === void 0 ? void 0 : _15.toString(),
            });
            throw new BadDataException("Status Page not found");
        }
        data.data.projectId = statuspage.projectId;
        logger.debug(`Updated Project ID: ${data.data.projectId}`, {
            projectId: (_16 = data.data.projectId) === null || _16 === void 0 ? void 0 : _16.toString(),
            statusPageId: (_17 = data.data.statusPageId) === null || _17 === void 0 ? void 0 : _17.toString(),
        });
        const isEmailSubscriber = Boolean(data.data.subscriberEmail);
        const isSubscriptionConfirmed = Boolean(data.data.isSubscriptionConfirmed);
        logger.debug(`Is Email Subscriber: ${isEmailSubscriber}`, {
            projectId: (_18 = data.data.projectId) === null || _18 === void 0 ? void 0 : _18.toString(),
            statusPageId: (_19 = data.data.statusPageId) === null || _19 === void 0 ? void 0 : _19.toString(),
        });
        logger.debug(`Is Subscription Confirmed: ${isSubscriptionConfirmed}`, {
            projectId: (_20 = data.data.projectId) === null || _20 === void 0 ? void 0 : _20.toString(),
            statusPageId: (_21 = data.data.statusPageId) === null || _21 === void 0 ? void 0 : _21.toString(),
        });
        if (isEmailSubscriber && !isSubscriptionConfirmed) {
            data.data.isSubscriptionConfirmed = false;
        }
        else {
            data.data.isSubscriptionConfirmed = true; // if the subscriber is not email, then set it to true for SMS subscribers / slack subscribers.
        }
        logger.debug(`Final Subscription Confirmed: ${data.data.isSubscriptionConfirmed}`, {
            projectId: (_22 = data.data.projectId) === null || _22 === void 0 ? void 0 : _22.toString(),
            statusPageId: (_23 = data.data.statusPageId) === null || _23 === void 0 ? void 0 : _23.toString(),
        });
        // if slack incoming webhook is provided, then see if it starts with https://hooks.slack.com/services/
        if (data.data.slackIncomingWebhookUrl) {
            logger.debug(`Slack Incoming Webhook URL: ${data.data.slackIncomingWebhookUrl}`, {
                projectId: (_24 = data.data.projectId) === null || _24 === void 0 ? void 0 : _24.toString(),
                statusPageId: (_25 = data.data.statusPageId) === null || _25 === void 0 ? void 0 : _25.toString(),
            });
            if (!SlackUtil.isValidSlackIncomingWebhookUrl(data.data.slackIncomingWebhookUrl)) {
                logger.debug("Invalid Slack Incoming Webhook URL.", {
                    projectId: (_26 = data.data.projectId) === null || _26 === void 0 ? void 0 : _26.toString(),
                    statusPageId: (_27 = data.data.statusPageId) === null || _27 === void 0 ? void 0 : _27.toString(),
                });
                throw new BadDataException("Invalid Slack Incoming Webhook URL.");
            }
        }
        // Validate Microsoft Teams webhook URL if provided
        if (data.data.microsoftTeamsIncomingWebhookUrl) {
            logger.debug(`Microsoft Teams Incoming Webhook URL: ${data.data.microsoftTeamsIncomingWebhookUrl}`, {
                projectId: (_28 = data.data.projectId) === null || _28 === void 0 ? void 0 : _28.toString(),
                statusPageId: (_29 = data.data.statusPageId) === null || _29 === void 0 ? void 0 : _29.toString(),
            });
            if (!MicrosoftTeamsUtil.isValidMicrosoftTeamsIncomingWebhookUrl(data.data.microsoftTeamsIncomingWebhookUrl)) {
                logger.debug("Invalid Microsoft Teams Incoming Webhook URL.", {
                    projectId: (_30 = data.data.projectId) === null || _30 === void 0 ? void 0 : _30.toString(),
                    statusPageId: (_31 = data.data.statusPageId) === null || _31 === void 0 ? void 0 : _31.toString(),
                });
                throw new BadDataException("Invalid Microsoft Teams Incoming Webhook URL.");
            }
        }
        data.data.subscriptionConfirmationToken = NumberUtil.getRandomNumber(100000, 999999).toString();
        logger.debug(`Subscription Confirmation Token: ${data.data.subscriptionConfirmationToken}`, {
            projectId: (_32 = data.data.projectId) === null || _32 === void 0 ? void 0 : _32.toString(),
            statusPageId: (_33 = data.data.statusPageId) === null || _33 === void 0 ? void 0 : _33.toString(),
        });
        logger.debug("onBeforeCreate processed data:", {
            projectId: (_34 = data.data.projectId) === null || _34 === void 0 ? void 0 : _34.toString(),
            statusPageId: (_35 = data.data.statusPageId) === null || _35 === void 0 ? void 0 : _35.toString(),
        });
        logger.debug(data, {
            projectId: (_36 = data.data.projectId) === null || _36 === void 0 ? void 0 : _36.toString(),
            statusPageId: (_37 = data.data.statusPageId) === null || _37 === void 0 ? void 0 : _37.toString(),
        });
        return { createBy: data, carryForward: statuspage };
    }
    async onCreateSuccess(onCreate, createdItem) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
        logger.debug("onCreateSuccess called with createdItem:", {
            projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
        });
        logger.debug(createdItem, {
            projectId: (_b = createdItem.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
        });
        if (!createdItem.statusPageId) {
            logger.debug("Status Page ID is missing in createdItem.", {
                projectId: (_c = createdItem.projectId) === null || _c === void 0 ? void 0 : _c.toString(),
            });
            return createdItem;
        }
        const statusPageURL = await StatusPageService.getStatusPageURL(createdItem.statusPageId);
        logger.debug(`Status Page URL: ${statusPageURL}`, {
            projectId: (_d = createdItem.projectId) === null || _d === void 0 ? void 0 : _d.toString(),
        });
        const statusPageName = onCreate.carryForward.pageTitle ||
            onCreate.carryForward.name ||
            "Status Page";
        logger.debug(`Status Page Name: ${statusPageName}`, {
            projectId: (_e = createdItem.projectId) === null || _e === void 0 ? void 0 : _e.toString(),
        });
        const unsubscribeLink = this.getUnsubscribeLink(URL.fromString(statusPageURL), createdItem.id).toString();
        logger.debug(`Unsubscribe Link: ${unsubscribeLink}`, {
            projectId: (_f = createdItem.projectId) === null || _f === void 0 ? void 0 : _f.toString(),
        });
        if (createdItem.statusPageId &&
            createdItem.subscriberPhone &&
            createdItem._id &&
            createdItem.sendYouHaveSubscribedMessage) {
            logger.debug("Subscriber has a phone number and sendYouHaveSubscribedMessage is true.", { projectId: (_g = createdItem.projectId) === null || _g === void 0 ? void 0 : _g.toString() });
            const statusPage = await StatusPageService.findOneBy({
                query: {
                    _id: createdItem.statusPageId.toString(),
                },
                select: {
                    callSmsConfig: {
                        _id: true,
                        twilioAccountSID: true,
                        twilioAuthToken: true,
                        twilioPrimaryPhoneNumber: true,
                        twilioSecondaryPhoneNumbers: true,
                    },
                },
                props: {
                    isRoot: true,
                    ignoreHooks: true,
                },
            });
            if (!statusPage) {
                logger.debug("Status Page not found.", {
                    projectId: (_h = createdItem.projectId) === null || _h === void 0 ? void 0 : _h.toString(),
                });
                return createdItem;
            }
            logger.debug(`Status Page Call SMS Config: ${JSON.stringify(statusPage.callSmsConfig)}`, { projectId: (_j = createdItem.projectId) === null || _j === void 0 ? void 0 : _j.toString() });
            SmsService.sendSms({
                to: createdItem.subscriberPhone,
                message: `You have been subscribed to ${statusPageName}. To unsubscribe, click on the link: ${unsubscribeLink}`,
            }, {
                projectId: createdItem.projectId,
                isSensitive: false,
                customTwilioConfig: ProjectCallSMSConfigService.toTwilioConfig(statusPage.callSmsConfig),
                statusPageId: createdItem.statusPageId,
            }).catch((err) => {
                var _a;
                logger.error(err, {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                });
            });
        }
        if (createdItem.statusPageId &&
            createdItem.subscriberEmail &&
            createdItem._id) {
            logger.debug("Subscriber has an email.", {
                projectId: (_k = createdItem.projectId) === null || _k === void 0 ? void 0 : _k.toString(),
            });
            const isSubscriptionConfirmed = Boolean(createdItem.isSubscriptionConfirmed);
            logger.debug(`Is Subscription Confirmed: ${isSubscriptionConfirmed}`, {
                projectId: (_l = createdItem.projectId) === null || _l === void 0 ? void 0 : _l.toString(),
            });
            if (!isSubscriptionConfirmed) {
                logger.debug("Subscription is not confirmed. Sending confirmation email.", { projectId: (_m = createdItem.projectId) === null || _m === void 0 ? void 0 : _m.toString() });
                await this.sendConfirmSubscriptionEmail({
                    subscriberId: createdItem.id,
                });
            }
            if (isSubscriptionConfirmed && createdItem.sendYouHaveSubscribedMessage) {
                logger.debug("Subscription is confirmed and sendYouHaveSubscribedMessage is true. Sending 'You have subscribed' email.", { projectId: (_o = createdItem.projectId) === null || _o === void 0 ? void 0 : _o.toString() });
                await this.sendYouHaveSubscribedEmail({
                    subscriberId: createdItem.id,
                });
            }
        }
        // if slack incoming webhook is provided, then send a message to the slack channel.
        if (createdItem.slackIncomingWebhookUrl) {
            logger.debug("Sending Slack notification for new subscriber.", {
                projectId: (_p = createdItem.projectId) === null || _p === void 0 ? void 0 : _p.toString(),
            });
            const slackMessage = `## 📢 New Subscription to ${statusPageName}

**You have successfully subscribed to receive status updates!**

🔗 **Status Page:** [${statusPageName}](${statusPageURL})
📧 **Manage Subscription:** [Update preferences or unsubscribe](${unsubscribeLink})

You will receive real-time notifications for:
• Incidents and outages 
• Scheduled maintenance events  
• Service announcements
• Status updates

Stay informed about service availability! 🚀`;
            logger.debug(`Slack Message: ${slackMessage}`, {
                projectId: (_q = createdItem.projectId) === null || _q === void 0 ? void 0 : _q.toString(),
            });
            SlackUtil.sendMessageToChannelViaIncomingWebhook({
                url: URL.fromString(createdItem.slackIncomingWebhookUrl.toString()),
                text: SlackUtil.convertMarkdownToSlackRichText(slackMessage),
            })
                .then(() => {
                var _a;
                logger.debug("Slack notification sent successfully.", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                });
            })
                .catch((err) => {
                var _a, _b;
                logger.error("Error sending Slack notification:", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                });
                logger.error(err, {
                    projectId: (_b = createdItem.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
                });
            });
        }
        // if generic webhook URL is provided and sendYouHaveSubscribedMessage is true, then ping the webhook with the subscription event.
        if (createdItem.subscriberWebhook &&
            createdItem.sendYouHaveSubscribedMessage) {
            logger.debug("Sending webhook notification for new subscriber.", {
                projectId: (_r = createdItem.projectId) === null || _r === void 0 ? void 0 : _r.toString(),
            });
            StatusPageSubscriberWebhookUtil.sendWebhookNotification({
                webhookUrl: URL.fromString(createdItem.subscriberWebhook.toString()),
                payload: {
                    eventType: "SubscriberSubscribed",
                    statusPageId: createdItem.statusPageId.toString(),
                    statusPageName: statusPageName,
                    statusPageUrl: statusPageURL,
                    unsubscribeUrl: unsubscribeLink,
                    data: {
                        message: `You have been subscribed to ${statusPageName}.`,
                    },
                },
            })
                .then(() => {
                var _a;
                logger.debug("Webhook notification sent successfully.", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                });
            })
                .catch((err) => {
                var _a, _b;
                logger.error("Error sending webhook notification:", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                });
                logger.error(err, {
                    projectId: (_b = createdItem.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
                });
            });
        }
        // if Microsoft Teams incoming webhook is provided and sendYouHaveSubscribedMessage is true, then send a message to the Teams channel.
        if (createdItem.microsoftTeamsIncomingWebhookUrl &&
            createdItem.sendYouHaveSubscribedMessage) {
            logger.debug("Sending Microsoft Teams notification for new subscriber.", {
                projectId: (_s = createdItem.projectId) === null || _s === void 0 ? void 0 : _s.toString(),
            });
            const teamsMessage = `## 📢 New Subscription to ${statusPageName}

**You have successfully subscribed to receive status updates!**

🔗 **Status Page:** [${statusPageName}](${statusPageURL})
📧 **Manage Subscription:** [Update preferences or unsubscribe](${unsubscribeLink})

You will receive real-time notifications for:
• Incidents and outages 
• Scheduled maintenance events  
• Service announcements
• Status updates

Stay informed about service availability! 🚀`;
            logger.debug(`Teams Message: ${teamsMessage}`, {
                projectId: (_t = createdItem.projectId) === null || _t === void 0 ? void 0 : _t.toString(),
            });
            MicrosoftTeamsUtil.sendMessageToChannelViaIncomingWebhook({
                url: URL.fromString(createdItem.microsoftTeamsIncomingWebhookUrl.toString()),
                text: teamsMessage,
            })
                .then(() => {
                var _a;
                logger.debug("Microsoft Teams notification sent successfully.", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                });
            })
                .catch((err) => {
                var _a, _b;
                logger.error("Error sending Microsoft Teams notification:", {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                });
                logger.error(err, {
                    projectId: (_b = createdItem.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
                });
            });
        }
        logger.debug("onCreateSuccess completed.", {
            projectId: (_u = createdItem.projectId) === null || _u === void 0 ? void 0 : _u.toString(),
        });
        return createdItem;
    }
    async sendConfirmSubscriptionEmail(data) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
        logger.debug("sendConfirmSubscriptionEmail called with data:", {
            statusPageSubscriberId: (_a = data.subscriberId) === null || _a === void 0 ? void 0 : _a.toString(),
        });
        logger.debug(data, {
            statusPageSubscriberId: (_b = data.subscriberId) === null || _b === void 0 ? void 0 : _b.toString(),
        });
        // get subscriber
        const subscriber = await this.findOneBy({
            query: {
                _id: data.subscriberId,
            },
            select: {
                statusPageId: true,
                subscriberEmail: true,
                subscriberPhone: true,
                projectId: true,
                subscriptionConfirmationToken: true,
                sendYouHaveSubscribedMessage: true,
            },
            props: {
                isRoot: true,
                ignoreHooks: true,
            },
        });
        logger.debug(`Found Subscriber: ${JSON.stringify(subscriber)}`, {
            statusPageSubscriberId: (_c = data.subscriberId) === null || _c === void 0 ? void 0 : _c.toString(),
        });
        // get status page
        if (!subscriber || !subscriber.statusPageId) {
            logger.debug("Subscriber or Status Page ID is missing.", {
                statusPageSubscriberId: (_d = data.subscriberId) === null || _d === void 0 ? void 0 : _d.toString(),
            });
            return;
        }
        const statusPage = await StatusPageService.findOneBy({
            query: {
                _id: subscriber.statusPageId.toString(),
            },
            select: {
                logoFileId: true,
                isPublicStatusPage: true,
                pageTitle: true,
                name: true,
                smtpConfig: {
                    _id: true,
                    transportType: true,
                    hostname: true,
                    port: true,
                    username: true,
                    password: true,
                    fromEmail: true,
                    fromName: true,
                    secure: true,
                    authType: true,
                    clientId: true,
                    clientSecret: true,
                    tokenUrl: true,
                    scope: true,
                    oauthProviderType: true,
                },
            },
            props: {
                isRoot: true,
                ignoreHooks: true,
            },
        });
        logger.debug(`Found Status Page: ${JSON.stringify(statusPage)}`, {
            statusPageSubscriberId: (_e = data.subscriberId) === null || _e === void 0 ? void 0 : _e.toString(),
        });
        if (!statusPage || !statusPage.id) {
            logger.debug("Status Page not found or ID is missing.", {
                statusPageSubscriberId: (_f = data.subscriberId) === null || _f === void 0 ? void 0 : _f.toString(),
            });
            return;
        }
        const statusPageURL = await StatusPageService.getStatusPageURL(statusPage.id);
        logger.debug(`Status Page URL: ${statusPageURL}`, {
            statusPageSubscriberId: (_g = data.subscriberId) === null || _g === void 0 ? void 0 : _g.toString(),
        });
        const statusPageName = statusPage.pageTitle || statusPage.name || "Status Page";
        logger.debug(`Status Page Name: ${statusPageName}`, {
            statusPageSubscriberId: (_h = data.subscriberId) === null || _h === void 0 ? void 0 : _h.toString(),
        });
        const host = await DatabaseConfig.getHost();
        logger.debug(`Host: ${host}`, {
            statusPageSubscriberId: (_j = data.subscriberId) === null || _j === void 0 ? void 0 : _j.toString(),
        });
        const httpProtocol = await DatabaseConfig.getHttpProtocol();
        logger.debug(`HTTP Protocol: ${httpProtocol}`, {
            statusPageSubscriberId: (_k = data.subscriberId) === null || _k === void 0 ? void 0 : _k.toString(),
        });
        const statusPageIdString = ((_l = statusPage.id) === null || _l === void 0 ? void 0 : _l.toString()) || ((_m = statusPage._id) === null || _m === void 0 ? void 0 : _m.toString()) || null;
        const confirmSubscriptionLink = this.getConfirmSubscriptionLink({
            statusPageUrl: statusPageURL,
            confirmationToken: subscriber.subscriptionConfirmationToken || "",
            statusPageSubscriberId: subscriber.id,
        }).toString();
        logger.debug(`Confirm Subscription Link: ${confirmSubscriptionLink}`, {
            statusPageSubscriberId: (_o = data.subscriberId) === null || _o === void 0 ? void 0 : _o.toString(),
        });
        if (subscriber.statusPageId &&
            subscriber.subscriberEmail &&
            subscriber._id) {
            const unsubscribeUrl = this.getUnsubscribeLink(URL.fromString(statusPageURL), subscriber.id).toString();
            logger.debug(`Unsubscribe URL: ${unsubscribeUrl}`, {
                statusPageSubscriberId: (_p = data.subscriberId) === null || _p === void 0 ? void 0 : _p.toString(),
            });
            const customTemplate = await StatusPageSubscriberNotificationTemplateService.getTemplateForStatusPage({
                statusPageId: statusPage.id,
                eventType: StatusPageSubscriberNotificationEventType.SubscriberSubscriptionConfirmation,
                notificationMethod: StatusPageSubscriberNotificationMethod.Email,
            });
            const templateVariables = {
                statusPageName: statusPageName,
                statusPageUrl: statusPageURL,
                confirmationUrl: confirmSubscriptionLink,
                unsubscribeUrl: unsubscribeUrl,
            };
            if ((customTemplate === null || customTemplate === void 0 ? void 0 : customTemplate.templateBody) && statusPage.smtpConfig) {
                /*
                 * Use custom template only when custom SMTP is configured (matches the
                 * pattern used elsewhere — without custom SMTP we keep the styled
                 * OneUptime default so emails still look right out-of-the-box).
                 */
                const compiledBody = StatusPageSubscriberNotificationTemplateServiceClass.compileTemplate(customTemplate.templateBody, templateVariables);
                const compiledSubject = customTemplate.emailSubject
                    ? StatusPageSubscriberNotificationTemplateServiceClass.compileTemplate(customTemplate.emailSubject, templateVariables)
                    : "Confirm your subscription to " + statusPageName;
                MailService.sendMail({
                    toEmail: subscriber.subscriberEmail,
                    templateType: EmailTemplateType.BlankTemplate,
                    vars: {
                        body: compiledBody,
                    },
                    subject: compiledSubject,
                }, {
                    projectId: subscriber.projectId,
                    mailServer: ProjectSMTPConfigService.toEmailServer(statusPage.smtpConfig),
                    statusPageId: statusPage.id,
                }).catch((err) => {
                    var _a;
                    logger.error(err, {
                        projectId: (_a = subscriber.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    });
                });
            }
            else {
                MailService.sendMail({
                    toEmail: subscriber.subscriberEmail,
                    templateType: EmailTemplateType.ConfirmStatusPageSubscription,
                    vars: {
                        statusPageName: statusPageName,
                        logoUrl: statusPage.logoFileId && statusPageIdString
                            ? new URL(httpProtocol, host)
                                .addRoute(StatusPageApiRoute)
                                .addRoute(`/logo/${statusPageIdString}`)
                                .toString()
                            : "",
                        statusPageUrl: statusPageURL,
                        isPublicStatusPage: statusPage.isPublicStatusPage
                            ? "true"
                            : "false",
                        confirmationUrl: confirmSubscriptionLink,
                        unsubscribeUrl: unsubscribeUrl,
                    },
                    subject: "Confirm your subscription to " + statusPageName,
                }, {
                    projectId: subscriber.projectId,
                    mailServer: ProjectSMTPConfigService.toEmailServer(statusPage.smtpConfig),
                    statusPageId: statusPage.id,
                }).catch((err) => {
                    var _a;
                    logger.error(err, {
                        projectId: (_a = subscriber.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    });
                });
            }
            logger.debug("Confirmation email sent.", {
                statusPageSubscriberId: (_q = data.subscriberId) === null || _q === void 0 ? void 0 : _q.toString(),
            });
        }
        else {
            logger.debug("Subscriber email or ID is missing.", {
                statusPageSubscriberId: (_r = data.subscriberId) === null || _r === void 0 ? void 0 : _r.toString(),
            });
        }
    }
    async sendYouHaveSubscribedEmail(data) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
        logger.debug("sendYouHaveSubscribedEmail called with data:", {
            statusPageSubscriberId: (_a = data.subscriberId) === null || _a === void 0 ? void 0 : _a.toString(),
        });
        logger.debug(data, {
            statusPageSubscriberId: (_b = data.subscriberId) === null || _b === void 0 ? void 0 : _b.toString(),
        });
        // get subscriber
        const subscriber = await this.findOneBy({
            query: {
                _id: data.subscriberId,
            },
            select: {
                statusPageId: true,
                subscriberEmail: true,
                subscriberPhone: true,
                projectId: true,
                sendYouHaveSubscribedMessage: true,
            },
            props: {
                isRoot: true,
                ignoreHooks: true,
            },
        });
        logger.debug(`Found Subscriber: ${JSON.stringify(subscriber)}`, {
            statusPageSubscriberId: (_c = data.subscriberId) === null || _c === void 0 ? void 0 : _c.toString(),
        });
        // get status page
        if (!subscriber || !subscriber.statusPageId) {
            logger.debug("Subscriber or Status Page ID is missing.", {
                statusPageSubscriberId: (_d = data.subscriberId) === null || _d === void 0 ? void 0 : _d.toString(),
            });
            return;
        }
        const statusPage = await StatusPageService.findOneBy({
            query: {
                _id: subscriber.statusPageId.toString(),
            },
            select: {
                logoFileId: true,
                isPublicStatusPage: true,
                pageTitle: true,
                name: true,
                smtpConfig: {
                    _id: true,
                    transportType: true,
                    hostname: true,
                    port: true,
                    username: true,
                    password: true,
                    fromEmail: true,
                    fromName: true,
                    secure: true,
                    authType: true,
                    clientId: true,
                    clientSecret: true,
                    tokenUrl: true,
                    scope: true,
                    oauthProviderType: true,
                },
            },
            props: {
                isRoot: true,
                ignoreHooks: true,
            },
        });
        logger.debug(`Found Status Page: ${JSON.stringify(statusPage)}`, {
            statusPageSubscriberId: (_e = data.subscriberId) === null || _e === void 0 ? void 0 : _e.toString(),
        });
        if (!statusPage || !statusPage.id) {
            logger.debug("Status Page not found or ID is missing.", {
                statusPageSubscriberId: (_f = data.subscriberId) === null || _f === void 0 ? void 0 : _f.toString(),
            });
            return;
        }
        const statusPageURL = await StatusPageService.getStatusPageURL(statusPage.id);
        logger.debug(`Status Page URL: ${statusPageURL}`, {
            statusPageSubscriberId: (_g = data.subscriberId) === null || _g === void 0 ? void 0 : _g.toString(),
        });
        const statusPageName = statusPage.pageTitle || statusPage.name || "Status Page";
        logger.debug(`Status Page Name: ${statusPageName}`, {
            statusPageSubscriberId: (_h = data.subscriberId) === null || _h === void 0 ? void 0 : _h.toString(),
        });
        const host = await DatabaseConfig.getHost();
        logger.debug(`Host: ${host}`, {
            statusPageSubscriberId: (_j = data.subscriberId) === null || _j === void 0 ? void 0 : _j.toString(),
        });
        const httpProtocol = await DatabaseConfig.getHttpProtocol();
        logger.debug(`HTTP Protocol: ${httpProtocol}`, {
            statusPageSubscriberId: (_k = data.subscriberId) === null || _k === void 0 ? void 0 : _k.toString(),
        });
        const statusPageIdString = ((_l = statusPage.id) === null || _l === void 0 ? void 0 : _l.toString()) || ((_m = statusPage._id) === null || _m === void 0 ? void 0 : _m.toString()) || null;
        const unsubscribeLink = this.getUnsubscribeLink(URL.fromString(statusPageURL), subscriber.id).toString();
        logger.debug(`Unsubscribe Link: ${unsubscribeLink}`, {
            statusPageSubscriberId: (_o = data.subscriberId) === null || _o === void 0 ? void 0 : _o.toString(),
        });
        if (subscriber.statusPageId &&
            subscriber.subscriberEmail &&
            subscriber._id) {
            logger.debug("Subscriber has an email and ID.", {
                statusPageSubscriberId: (_p = data.subscriberId) === null || _p === void 0 ? void 0 : _p.toString(),
            });
            const customTemplate = await StatusPageSubscriberNotificationTemplateService.getTemplateForStatusPage({
                statusPageId: statusPage.id,
                eventType: StatusPageSubscriberNotificationEventType.SubscriberSubscribed,
                notificationMethod: StatusPageSubscriberNotificationMethod.Email,
            });
            const templateVariables = {
                statusPageName: statusPageName,
                statusPageUrl: statusPageURL,
                unsubscribeUrl: unsubscribeLink,
            };
            if ((customTemplate === null || customTemplate === void 0 ? void 0 : customTemplate.templateBody) && statusPage.smtpConfig) {
                const compiledBody = StatusPageSubscriberNotificationTemplateServiceClass.compileTemplate(customTemplate.templateBody, templateVariables);
                const compiledSubject = customTemplate.emailSubject
                    ? StatusPageSubscriberNotificationTemplateServiceClass.compileTemplate(customTemplate.emailSubject, templateVariables)
                    : "You have been subscribed to " + statusPageName;
                MailService.sendMail({
                    toEmail: subscriber.subscriberEmail,
                    templateType: EmailTemplateType.BlankTemplate,
                    vars: {
                        body: compiledBody,
                    },
                    subject: compiledSubject,
                }, {
                    projectId: subscriber.projectId,
                    mailServer: ProjectSMTPConfigService.toEmailServer(statusPage.smtpConfig),
                    statusPageId: statusPage.id,
                }).catch((err) => {
                    var _a;
                    logger.error(err, {
                        projectId: (_a = subscriber.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    });
                });
            }
            else {
                MailService.sendMail({
                    toEmail: subscriber.subscriberEmail,
                    templateType: EmailTemplateType.SubscribedToStatusPage,
                    vars: {
                        statusPageName: statusPageName,
                        logoUrl: statusPage.logoFileId && statusPageIdString
                            ? new URL(httpProtocol, host)
                                .addRoute(StatusPageApiRoute)
                                .addRoute(`/logo/${statusPageIdString}`)
                                .toString()
                            : "",
                        statusPageUrl: statusPageURL,
                        isPublicStatusPage: statusPage.isPublicStatusPage
                            ? "true"
                            : "false",
                        unsubscribeUrl: unsubscribeLink,
                    },
                    subject: "You have been subscribed to " + statusPageName,
                }, {
                    projectId: subscriber.projectId,
                    mailServer: ProjectSMTPConfigService.toEmailServer(statusPage.smtpConfig),
                    statusPageId: statusPage.id,
                }).catch((err) => {
                    var _a, _b;
                    logger.error("Error sending subscription email:", {
                        projectId: (_a = subscriber.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    });
                    logger.error(err, {
                        projectId: (_b = subscriber.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
                    });
                });
            }
            logger.debug("Subscription email sent successfully.", {
                statusPageSubscriberId: (_q = data.subscriberId) === null || _q === void 0 ? void 0 : _q.toString(),
            });
        }
        else {
            logger.debug("Subscriber email or ID is missing.", {
                statusPageSubscriberId: (_r = data.subscriberId) === null || _r === void 0 ? void 0 : _r.toString(),
            });
        }
    }
    getConfirmSubscriptionLink(data) {
        var _a, _b, _c;
        logger.debug("getConfirmSubscriptionLink called with data:", {
            statusPageSubscriberId: (_a = data.statusPageSubscriberId) === null || _a === void 0 ? void 0 : _a.toString(),
        });
        logger.debug(data, {
            statusPageSubscriberId: (_b = data.statusPageSubscriberId) === null || _b === void 0 ? void 0 : _b.toString(),
        });
        const confirmSubscriptionLink = URL.fromString(data.statusPageUrl).addRoute(`/confirm-subscription/${data.statusPageSubscriberId.toString()}?verification-token=${data.confirmationToken}`);
        logger.debug(`Generated Confirm Subscription Link: ${confirmSubscriptionLink.toString()}`, {
            statusPageSubscriberId: (_c = data.statusPageSubscriberId) === null || _c === void 0 ? void 0 : _c.toString(),
        });
        return confirmSubscriptionLink;
    }
    async getSubscribersByStatusPage(statusPageId, props) {
        logger.debug("getSubscribersByStatusPage called with statusPageId:", {
            statusPageId: statusPageId === null || statusPageId === void 0 ? void 0 : statusPageId.toString(),
        });
        logger.debug(statusPageId, {
            statusPageId: statusPageId === null || statusPageId === void 0 ? void 0 : statusPageId.toString(),
        });
        logger.debug("DatabaseCommonInteractionProps:", {
            statusPageId: statusPageId === null || statusPageId === void 0 ? void 0 : statusPageId.toString(),
        });
        logger.debug(props, {
            statusPageId: statusPageId === null || statusPageId === void 0 ? void 0 : statusPageId.toString(),
        });
        const subscribers = await this.findBy({
            query: {
                statusPageId: statusPageId,
                isUnsubscribed: false,
                isSubscriptionConfirmed: true,
            },
            select: {
                _id: true,
                subscriberEmail: true,
                subscriberPhone: true,
                subscriberWebhook: true,
                slackIncomingWebhookUrl: true,
                microsoftTeamsIncomingWebhookUrl: true,
                isSubscribedToAllResources: true,
                statusPageResources: true,
                isSubscribedToAllEventTypes: true,
                statusPageEventTypes: true,
            },
            skip: 0,
            limit: LIMIT_MAX,
            props: props,
        });
        logger.debug("Found subscribers:", {
            statusPageId: statusPageId === null || statusPageId === void 0 ? void 0 : statusPageId.toString(),
        });
        logger.debug(subscribers, {
            statusPageId: statusPageId === null || statusPageId === void 0 ? void 0 : statusPageId.toString(),
        });
        return subscribers;
    }
    getUnsubscribeLink(statusPageUrl, statusPageSubscriberId) {
        logger.debug("getUnsubscribeLink called with statusPageUrl:", {
            statusPageSubscriberId: statusPageSubscriberId === null || statusPageSubscriberId === void 0 ? void 0 : statusPageSubscriberId.toString(),
        });
        logger.debug(statusPageUrl, {
            statusPageSubscriberId: statusPageSubscriberId === null || statusPageSubscriberId === void 0 ? void 0 : statusPageSubscriberId.toString(),
        });
        logger.debug("statusPageSubscriberId:", {
            statusPageSubscriberId: statusPageSubscriberId === null || statusPageSubscriberId === void 0 ? void 0 : statusPageSubscriberId.toString(),
        });
        logger.debug(statusPageSubscriberId, {
            statusPageSubscriberId: statusPageSubscriberId === null || statusPageSubscriberId === void 0 ? void 0 : statusPageSubscriberId.toString(),
        });
        const unsubscribeLink = URL.fromString(statusPageUrl.toString()).addRoute("/update-subscription/" + statusPageSubscriberId.toString());
        logger.debug("Generated Unsubscribe Link:", {
            statusPageSubscriberId: statusPageSubscriberId === null || statusPageSubscriberId === void 0 ? void 0 : statusPageSubscriberId.toString(),
        });
        logger.debug(unsubscribeLink, {
            statusPageSubscriberId: statusPageSubscriberId === null || statusPageSubscriberId === void 0 ? void 0 : statusPageSubscriberId.toString(),
        });
        return unsubscribeLink;
    }
    shouldSendNotification(data) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1;
        logger.debug("shouldSendNotification called with data:", {
            statusPageId: (_b = (_a = data.statusPage) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.toString(),
        });
        logger.debug(data, {
            statusPageId: (_d = (_c = data.statusPage) === null || _c === void 0 ? void 0 : _c.id) === null || _d === void 0 ? void 0 : _d.toString(),
        });
        let shouldSendNotification = true; // default to true.
        if (data.subscriber.isUnsubscribed) {
            logger.debug("Subscriber is unsubscribed.", {
                statusPageId: (_f = (_e = data.statusPage) === null || _e === void 0 ? void 0 : _e.id) === null || _f === void 0 ? void 0 : _f.toString(),
            });
            shouldSendNotification = false;
            return shouldSendNotification;
        }
        if (data.statusPage.allowSubscribersToChooseResources &&
            !data.subscriber.isSubscribedToAllResources &&
            !(data.eventType === StatusPageEventType.Announcement &&
                data.statusPageResources.length === 0) // announcements with no monitors don't use resource filtering
        ) {
            logger.debug("Subscriber can choose resources and is not subscribed to all resources.", { statusPageId: (_h = (_g = data.statusPage) === null || _g === void 0 ? void 0 : _g.id) === null || _h === void 0 ? void 0 : _h.toString() });
            const subscriberResourceIds = ((_j = data.subscriber.statusPageResources) === null || _j === void 0 ? void 0 : _j.map((resource) => {
                var _a;
                return (_a = resource.id) === null || _a === void 0 ? void 0 : _a.toString();
            })) || [];
            logger.debug(`Subscriber Resource IDs: ${subscriberResourceIds}`, {
                statusPageId: (_l = (_k = data.statusPage) === null || _k === void 0 ? void 0 : _k.id) === null || _l === void 0 ? void 0 : _l.toString(),
            });
            let shouldSendNotificationForResource = false;
            if (subscriberResourceIds.length === 0) {
                logger.debug("Subscriber has no resource IDs.", {
                    statusPageId: (_o = (_m = data.statusPage) === null || _m === void 0 ? void 0 : _m.id) === null || _o === void 0 ? void 0 : _o.toString(),
                });
                shouldSendNotificationForResource = false;
            }
            else {
                for (const resource of data.statusPageResources) {
                    logger.debug(`Checking resource: ${resource.id}`, {
                        statusPageId: (_q = (_p = data.statusPage) === null || _p === void 0 ? void 0 : _p.id) === null || _q === void 0 ? void 0 : _q.toString(),
                    });
                    if (subscriberResourceIds.includes((_r = resource.id) === null || _r === void 0 ? void 0 : _r.toString())) {
                        logger.debug("Resource ID matches subscriber's resource ID.", {
                            statusPageId: (_t = (_s = data.statusPage) === null || _s === void 0 ? void 0 : _s.id) === null || _t === void 0 ? void 0 : _t.toString(),
                        });
                        shouldSendNotificationForResource = true;
                    }
                }
            }
            if (!shouldSendNotificationForResource) {
                logger.debug("Should not send notification for resource.", {
                    statusPageId: (_v = (_u = data.statusPage) === null || _u === void 0 ? void 0 : _u.id) === null || _v === void 0 ? void 0 : _v.toString(),
                });
                shouldSendNotification = false;
            }
        }
        // now do for event types
        if (data.statusPage.allowSubscribersToChooseEventTypes &&
            !data.subscriber.isSubscribedToAllEventTypes) {
            logger.debug("Subscriber can choose event types and is not subscribed to all event types.", { statusPageId: (_x = (_w = data.statusPage) === null || _w === void 0 ? void 0 : _w.id) === null || _x === void 0 ? void 0 : _x.toString() });
            const subscriberEventTypes = data.subscriber.statusPageEventTypes || [];
            logger.debug(`Subscriber Event Types: ${subscriberEventTypes}`, {
                statusPageId: (_z = (_y = data.statusPage) === null || _y === void 0 ? void 0 : _y.id) === null || _z === void 0 ? void 0 : _z.toString(),
            });
            let shouldSendNotificationForEventType = false;
            if (subscriberEventTypes.includes(data.eventType)) {
                logger.debug("Event type matches subscriber's event type.", {
                    statusPageId: (_1 = (_0 = data.statusPage) === null || _0 === void 0 ? void 0 : _0.id) === null || _1 === void 0 ? void 0 : _1.toString(),
                });
                shouldSendNotificationForEventType = true;
            }
            if (!shouldSendNotificationForEventType) {
                logger.debug("Should not send notification for event type.", {});
                shouldSendNotification = false;
            }
        }
        logger.debug(`Final decision on shouldSendNotification: ${shouldSendNotification}`, {});
        return shouldSendNotification;
    }
    async getStatusPagesToSendNotification(statusPageIds) {
        logger.debug("getStatusPagesToSendNotification called with statusPageIds:", {});
        logger.debug(statusPageIds, {});
        const statusPages = await StatusPageService.findBy({
            query: {
                _id: QueryHelper.any(statusPageIds),
            },
            props: {
                isRoot: true,
                ignoreHooks: true,
            },
            skip: 0,
            limit: LIMIT_PER_PROJECT,
            select: {
                _id: true,
                name: true,
                pageTitle: true,
                projectId: true,
                isPublicStatusPage: true,
                logoFileId: true,
                allowSubscribersToChooseResources: true,
                subscriberEmailNotificationFooterText: true,
                enableCustomSubscriberEmailNotificationFooterText: true,
                allowSubscribersToChooseEventTypes: true,
                smtpConfig: {
                    _id: true,
                    transportType: true,
                    hostname: true,
                    port: true,
                    username: true,
                    password: true,
                    fromEmail: true,
                    fromName: true,
                    secure: true,
                    authType: true,
                    clientId: true,
                    clientSecret: true,
                    tokenUrl: true,
                    scope: true,
                    oauthProviderType: true,
                },
                callSmsConfig: {
                    _id: true,
                    twilioAccountSID: true,
                    twilioAuthToken: true,
                    twilioPrimaryPhoneNumber: true,
                    twilioSecondaryPhoneNumbers: true,
                },
                subscriberTimezones: true,
                reportDataInDays: true,
                isReportEnabled: true,
                showAnnouncementsOnStatusPage: true,
                showIncidentsOnStatusPage: true,
                showScheduledMaintenanceEventsOnStatusPage: true,
            },
        });
        logger.debug("Found status pages:", {});
        logger.debug(statusPages, {});
        return statusPages;
    }
    async testSubscriberWebhook(data) {
        var _a, _b;
        // basic validation - must be a valid URL
        let parsedUrl;
        try {
            parsedUrl = URL.fromString(data.webhookUrl);
        }
        catch (_c) {
            throw new BadDataException("Invalid Webhook URL");
        }
        // get the status page info
        const statusPage = await StatusPageService.findOneById({
            id: data.statusPageId,
            props: {
                isRoot: true,
            },
            select: {
                name: true,
                pageTitle: true,
                projectId: true,
                _id: true,
            },
        });
        if (!statusPage) {
            throw new BadDataException("Status page not found");
        }
        const statusPageName = statusPage.pageTitle || statusPage.name || "Status Page";
        const statusPageURL = await StatusPageService.getStatusPageURL(statusPage.id);
        try {
            await StatusPageSubscriberWebhookUtil.sendWebhookNotification({
                webhookUrl: parsedUrl,
                payload: {
                    eventType: "TestNotification",
                    statusPageId: statusPage.id.toString(),
                    statusPageName: statusPageName,
                    statusPageUrl: statusPageURL,
                    unsubscribeUrl: "",
                    data: {
                        message: "This is a test notification from OneUptime. Your webhook is configured correctly.",
                    },
                },
            });
        }
        catch (error) {
            logger.error("Error sending test webhook notification:", {
                projectId: (_a = statusPage === null || statusPage === void 0 ? void 0 : statusPage.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
            });
            logger.error(error, {
                projectId: (_b = statusPage === null || statusPage === void 0 ? void 0 : statusPage.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
            });
            throw error;
        }
    }
    async testSlackWebhook(data) {
        var _a, _b;
        // Validate the webhook URL
        if (!data.webhookUrl.startsWith("https://hooks.slack.com/services/")) {
            throw new BadDataException("Invalid Slack webhook URL");
        }
        // Get status page info
        const statusPage = await StatusPageService.findOneById({
            id: data.statusPageId,
            props: {
                isRoot: true,
            },
            select: {
                name: true,
                pageTitle: true,
                projectId: true,
                _id: true,
            },
        });
        if (!statusPage) {
            throw new BadDataException("Status page not found");
        }
        // Create test notification message
        const statusPageName = statusPage.pageTitle || statusPage.name || "Status Page";
        const statusPageURL = await StatusPageService.getStatusPageURL(statusPage.id);
        // Create markdown message for Slack
        const markdownMessage = `## Test Notification - ${statusPageName}

**This is a test notification from OneUptime.**

You have successfully configured Slack notifications for this status page.

You will receive real-time notifications for:
- Incidents
- Scheduled Maintenance Events
- Status Updates
- Announcements

[View Status Page](${statusPageURL})`;
        // Send the test notification
        try {
            await SlackUtil.sendMessageToChannelViaIncomingWebhook({
                url: URL.fromString(data.webhookUrl),
                text: SlackUtil.convertMarkdownToSlackRichText(markdownMessage),
            });
        }
        catch (error) {
            logger.error("Error sending test Slack notification:", {
                projectId: (_a = statusPage === null || statusPage === void 0 ? void 0 : statusPage.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
            });
            logger.error(error, {
                projectId: (_b = statusPage === null || statusPage === void 0 ? void 0 : statusPage.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
            });
            throw error;
        }
    }
}
__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, "sendConfirmSubscriptionEmail", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "sendYouHaveSubscribedEmail", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID, Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getSubscribersByStatusPage", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Array]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getStatusPagesToSendNotification", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "testSubscriberWebhook", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "testSlackWebhook", null);
export default new Service();
//# sourceMappingURL=StatusPageSubscriberService.js.map