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 DatabaseConfig from "../DatabaseConfig";
import logger from "../Utils/Logger";
import DatabaseService from "./DatabaseService";
import MailService from "./MailService";
import ProjectSMTPConfigService from "./ProjectSmtpConfigService";
import StatusPageService from "./StatusPageService";
import { StatusPageApiRoute } from "../../ServiceRoute";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import URL from "../../Types/API/URL";
import OneUptimeDate from "../../Types/Date";
import EmailTemplateType from "../../Types/Email/EmailTemplateType";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import Model from "../../Models/DatabaseModels/StatusPagePrivateUser";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        // check if this user is already invited.
        if (createBy.data.statusPageId && createBy.data.email) {
            const statusPageUser = await this.findOneBy({
                query: {
                    email: createBy.data.email,
                    statusPageId: createBy.data.statusPageId,
                },
                props: {
                    isRoot: true,
                },
                select: {
                    _id: true,
                },
            });
            if (statusPageUser) {
                throw new BadDataException("This user is already invited to this status page.");
            }
        }
        return {
            createBy: createBy,
            carryForward: null,
        };
    }
    async onCreateSuccess(_onCreate, createdItem) {
        var _a, _b;
        // send email to the user.
        const token = ObjectID.generate().toString();
        await this.updateOneById({
            id: createdItem.id,
            data: {
                resetPasswordToken: token,
                resetPasswordExpires: OneUptimeDate.getOneDayAfter(),
            },
            props: {
                isRoot: true,
                ignoreHooks: true,
            },
        });
        if (createdItem.isSsoUser) {
            return createdItem;
        }
        const statusPage = await StatusPageService.findOneById({
            id: createdItem.statusPageId,
            props: {
                isRoot: true,
                ignoreHooks: true,
            },
            select: {
                _id: true,
                name: true,
                pageTitle: true,
                logoFileId: true,
                projectId: 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,
                },
            },
        });
        if (!statusPage) {
            throw new BadDataException("Status Page not found");
        }
        const statusPageName = statusPage.pageTitle || statusPage.name;
        const statusPageURL = await StatusPageService.getStatusPageURL(statusPage.id);
        const host = await DatabaseConfig.getHost();
        const httpProtocol = await DatabaseConfig.getHttpProtocol();
        const statusPageIdString = ((_a = statusPage.id) === null || _a === void 0 ? void 0 : _a.toString()) || ((_b = statusPage._id) === null || _b === void 0 ? void 0 : _b.toString()) || null;
        MailService.sendMail({
            toEmail: createdItem.email,
            subject: "You have been invited to " + statusPageName,
            templateType: EmailTemplateType.StatusPageWelcomeEmail,
            vars: {
                statusPageName: statusPageName,
                statusPageUrl: statusPageURL,
                logoUrl: statusPage.logoFileId && statusPageIdString
                    ? new URL(httpProtocol, host)
                        .addRoute(StatusPageApiRoute)
                        .addRoute(`/logo/${statusPageIdString}`)
                        .toString()
                    : "",
                homeURL: statusPageURL,
                tokenVerifyUrl: URL.fromString(statusPageURL)
                    .addRoute("/reset-password/" + token)
                    .toString(),
            },
        }, {
            projectId: statusPage.projectId,
            mailServer: ProjectSMTPConfigService.toEmailServer(statusPage.smtpConfig),
            statusPageId: statusPage.id,
        }).catch((err) => {
            logger.error(err);
        });
        return createdItem;
    }
}
__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);
export default new Service();
//# sourceMappingURL=StatusPagePrivateUserService.js.map