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 Domain from "../Types/Domain";
import DatabaseService from "./DatabaseService";
import BadDataException from "../../Types/Exception/BadDataException";
import Text from "../../Types/Text";
import Model from "../../Models/DatabaseModels/Domain";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        var _a;
        if (createBy.data.domain) {
            let domain = undefined;
            if (createBy.data.domain instanceof Domain) {
                domain = createBy.data.domain.toString();
            }
            else if (typeof createBy.data.domain === "string") {
                domain = createBy.data.domain;
            }
            else {
                throw new BadDataException("Domain must be a string or an instance of Domain.");
            }
            createBy.data.domain = new Domain(domain.trim().toLowerCase());
        }
        /*
         * Prevent setting isVerified during creation, EXCEPT for test domains
         * Test domains can be auto-verified since they are reserved TLDs that can't have real DNS records
         */
        if (!createBy.props.isRoot && createBy.data.isVerified) {
            const domainStr = ((_a = createBy.data.domain) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            if (!Domain.isTestDomain(domainStr)) {
                throw new BadDataException("Domain cannot be verified during creation. Please verify the domain after creation. Please set isVerified to false.");
            }
        }
        createBy.data.domainVerificationText =
            "oneuptime-verification-" + Text.generateRandomText(20);
        return Promise.resolve({ createBy, carryForward: null });
    }
    async onBeforeUpdate(updateBy) {
        var _a, _b;
        if (updateBy.data.isVerified && !updateBy.props.isRoot) {
            const projectId = updateBy.query.projectId || updateBy.props.tenantId;
            if (!projectId) {
                throw new BadDataException("Project ID is required to verify the domain.");
            }
            // check the verification of the domain.
            const items = await this.findBy({
                query: Object.assign({ projectId }, updateBy.query),
                select: {
                    domain: true,
                    domainVerificationText: true,
                },
                limit: LIMIT_PER_PROJECT,
                skip: 0,
                props: {
                    isRoot: true,
                },
            });
            for (const item of items) {
                const domain = (_a = item === null || item === void 0 ? void 0 : item.domain) === null || _a === void 0 ? void 0 : _a.toString();
                const verificationText = (_b = item === null || item === void 0 ? void 0 : item.domainVerificationText) === null || _b === void 0 ? void 0 : _b.toString();
                if (!domain) {
                    throw new BadDataException("Domain not found.");
                }
                if (!verificationText) {
                    throw new BadDataException("Domain verification text with id " +
                        updateBy.query._id +
                        " not found.");
                }
                // Skip DNS verification for test domains (reserved TLDs for testing)
                if (!Domain.isTestDomain(domain)) {
                    const isVerified = await Domain.verifyTxtRecord(domain, verificationText);
                    if (!isVerified) {
                        throw new BadDataException("Verification TXT record " +
                            verificationText +
                            " not found in domain " +
                            domain +
                            ". Please add a TXT record to verify the domain. If you have already added the TXT record, please wait for few hours to let DNS to propagate.");
                    }
                }
            }
        }
        return { carryForward: null, updateBy };
    }
}
__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]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeUpdate", null);
export default new Service();
//# sourceMappingURL=DomainService.js.map