var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
import * as plugins from '../../plugins.js';
import { DcRouterDb } from '../classes.dcrouter-db.js';
const TTL = plugins.smartdata.smartdataTtlValues;
/**
 * Helper to get the smartdata database instance
 */
const getDb = () => DcRouterDb.getInstance().getDb();
/**
 * CachedEmail - Stores email queue items in the cache
 *
 * Used for persistent email queue storage, tracking delivery status,
 * and maintaining email history for the configured TTL period.
 */
let CachedEmail = (() => {
    let _classDecorators = [plugins.smartdata.Collection(() => getDb())];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = plugins.smartdata.SmartdataCachedDocument;
    let _id_decorators;
    let _id_initializers = [];
    let _id_extraInitializers = [];
    let _messageId_decorators;
    let _messageId_initializers = [];
    let _messageId_extraInitializers = [];
    let _from_decorators;
    let _from_initializers = [];
    let _from_extraInitializers = [];
    let _to_decorators;
    let _to_initializers = [];
    let _to_extraInitializers = [];
    let _cc_decorators;
    let _cc_initializers = [];
    let _cc_extraInitializers = [];
    let _bcc_decorators;
    let _bcc_initializers = [];
    let _bcc_extraInitializers = [];
    let _subject_decorators;
    let _subject_initializers = [];
    let _subject_extraInitializers = [];
    let _rawContent_decorators;
    let _rawContent_initializers = [];
    let _rawContent_extraInitializers = [];
    let _status_decorators;
    let _status_initializers = [];
    let _status_extraInitializers = [];
    let _attempts_decorators;
    let _attempts_initializers = [];
    let _attempts_extraInitializers = [];
    let _maxAttempts_decorators;
    let _maxAttempts_initializers = [];
    let _maxAttempts_extraInitializers = [];
    let _nextAttempt_decorators;
    let _nextAttempt_initializers = [];
    let _nextAttempt_extraInitializers = [];
    let _lastError_decorators;
    let _lastError_initializers = [];
    let _lastError_extraInitializers = [];
    let _deliveredAt_decorators;
    let _deliveredAt_initializers = [];
    let _deliveredAt_extraInitializers = [];
    let _senderDomain_decorators;
    let _senderDomain_initializers = [];
    let _senderDomain_extraInitializers = [];
    let _priority_decorators;
    let _priority_initializers = [];
    let _priority_extraInitializers = [];
    let _routeData_decorators;
    let _routeData_initializers = [];
    let _routeData_extraInitializers = [];
    let _dkimSigned_decorators;
    let _dkimSigned_initializers = [];
    let _dkimSigned_extraInitializers = [];
    var CachedEmail = class extends _classSuper {
        static { _classThis = this; }
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _id_decorators = [plugins.smartdata.unI(), plugins.smartdata.svDb()];
            _messageId_decorators = [plugins.smartdata.svDb()];
            _from_decorators = [plugins.smartdata.svDb()];
            _to_decorators = [plugins.smartdata.svDb()];
            _cc_decorators = [plugins.smartdata.svDb()];
            _bcc_decorators = [plugins.smartdata.svDb()];
            _subject_decorators = [plugins.smartdata.svDb()];
            _rawContent_decorators = [plugins.smartdata.svDb()];
            _status_decorators = [plugins.smartdata.svDb()];
            _attempts_decorators = [plugins.smartdata.svDb()];
            _maxAttempts_decorators = [plugins.smartdata.svDb()];
            _nextAttempt_decorators = [plugins.smartdata.svDb()];
            _lastError_decorators = [plugins.smartdata.svDb()];
            _deliveredAt_decorators = [plugins.smartdata.svDb()];
            _senderDomain_decorators = [plugins.smartdata.svDb()];
            _priority_decorators = [plugins.smartdata.svDb()];
            _routeData_decorators = [plugins.smartdata.svDb()];
            _dkimSigned_decorators = [plugins.smartdata.svDb()];
            __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: obj => "id" in obj, get: obj => obj.id, set: (obj, value) => { obj.id = value; } }, metadata: _metadata }, _id_initializers, _id_extraInitializers);
            __esDecorate(null, null, _messageId_decorators, { kind: "field", name: "messageId", static: false, private: false, access: { has: obj => "messageId" in obj, get: obj => obj.messageId, set: (obj, value) => { obj.messageId = value; } }, metadata: _metadata }, _messageId_initializers, _messageId_extraInitializers);
            __esDecorate(null, null, _from_decorators, { kind: "field", name: "from", static: false, private: false, access: { has: obj => "from" in obj, get: obj => obj.from, set: (obj, value) => { obj.from = value; } }, metadata: _metadata }, _from_initializers, _from_extraInitializers);
            __esDecorate(null, null, _to_decorators, { kind: "field", name: "to", static: false, private: false, access: { has: obj => "to" in obj, get: obj => obj.to, set: (obj, value) => { obj.to = value; } }, metadata: _metadata }, _to_initializers, _to_extraInitializers);
            __esDecorate(null, null, _cc_decorators, { kind: "field", name: "cc", static: false, private: false, access: { has: obj => "cc" in obj, get: obj => obj.cc, set: (obj, value) => { obj.cc = value; } }, metadata: _metadata }, _cc_initializers, _cc_extraInitializers);
            __esDecorate(null, null, _bcc_decorators, { kind: "field", name: "bcc", static: false, private: false, access: { has: obj => "bcc" in obj, get: obj => obj.bcc, set: (obj, value) => { obj.bcc = value; } }, metadata: _metadata }, _bcc_initializers, _bcc_extraInitializers);
            __esDecorate(null, null, _subject_decorators, { kind: "field", name: "subject", static: false, private: false, access: { has: obj => "subject" in obj, get: obj => obj.subject, set: (obj, value) => { obj.subject = value; } }, metadata: _metadata }, _subject_initializers, _subject_extraInitializers);
            __esDecorate(null, null, _rawContent_decorators, { kind: "field", name: "rawContent", static: false, private: false, access: { has: obj => "rawContent" in obj, get: obj => obj.rawContent, set: (obj, value) => { obj.rawContent = value; } }, metadata: _metadata }, _rawContent_initializers, _rawContent_extraInitializers);
            __esDecorate(null, null, _status_decorators, { kind: "field", name: "status", static: false, private: false, access: { has: obj => "status" in obj, get: obj => obj.status, set: (obj, value) => { obj.status = value; } }, metadata: _metadata }, _status_initializers, _status_extraInitializers);
            __esDecorate(null, null, _attempts_decorators, { kind: "field", name: "attempts", static: false, private: false, access: { has: obj => "attempts" in obj, get: obj => obj.attempts, set: (obj, value) => { obj.attempts = value; } }, metadata: _metadata }, _attempts_initializers, _attempts_extraInitializers);
            __esDecorate(null, null, _maxAttempts_decorators, { kind: "field", name: "maxAttempts", static: false, private: false, access: { has: obj => "maxAttempts" in obj, get: obj => obj.maxAttempts, set: (obj, value) => { obj.maxAttempts = value; } }, metadata: _metadata }, _maxAttempts_initializers, _maxAttempts_extraInitializers);
            __esDecorate(null, null, _nextAttempt_decorators, { kind: "field", name: "nextAttempt", static: false, private: false, access: { has: obj => "nextAttempt" in obj, get: obj => obj.nextAttempt, set: (obj, value) => { obj.nextAttempt = value; } }, metadata: _metadata }, _nextAttempt_initializers, _nextAttempt_extraInitializers);
            __esDecorate(null, null, _lastError_decorators, { kind: "field", name: "lastError", static: false, private: false, access: { has: obj => "lastError" in obj, get: obj => obj.lastError, set: (obj, value) => { obj.lastError = value; } }, metadata: _metadata }, _lastError_initializers, _lastError_extraInitializers);
            __esDecorate(null, null, _deliveredAt_decorators, { kind: "field", name: "deliveredAt", static: false, private: false, access: { has: obj => "deliveredAt" in obj, get: obj => obj.deliveredAt, set: (obj, value) => { obj.deliveredAt = value; } }, metadata: _metadata }, _deliveredAt_initializers, _deliveredAt_extraInitializers);
            __esDecorate(null, null, _senderDomain_decorators, { kind: "field", name: "senderDomain", static: false, private: false, access: { has: obj => "senderDomain" in obj, get: obj => obj.senderDomain, set: (obj, value) => { obj.senderDomain = value; } }, metadata: _metadata }, _senderDomain_initializers, _senderDomain_extraInitializers);
            __esDecorate(null, null, _priority_decorators, { kind: "field", name: "priority", static: false, private: false, access: { has: obj => "priority" in obj, get: obj => obj.priority, set: (obj, value) => { obj.priority = value; } }, metadata: _metadata }, _priority_initializers, _priority_extraInitializers);
            __esDecorate(null, null, _routeData_decorators, { kind: "field", name: "routeData", static: false, private: false, access: { has: obj => "routeData" in obj, get: obj => obj.routeData, set: (obj, value) => { obj.routeData = value; } }, metadata: _metadata }, _routeData_initializers, _routeData_extraInitializers);
            __esDecorate(null, null, _dkimSigned_decorators, { kind: "field", name: "dkimSigned", static: false, private: false, access: { has: obj => "dkimSigned" in obj, get: obj => obj.dkimSigned, set: (obj, value) => { obj.dkimSigned = value; } }, metadata: _metadata }, _dkimSigned_initializers, _dkimSigned_extraInitializers);
            __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            CachedEmail = _classThis = _classDescriptor.value;
            if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
            __runInitializers(_classThis, _classExtraInitializers);
        }
        /**
         * Unique identifier for this email
         */
        id = __runInitializers(this, _id_initializers, void 0);
        /**
         * Email message ID (RFC 822 Message-ID header)
         */
        messageId = (__runInitializers(this, _id_extraInitializers), __runInitializers(this, _messageId_initializers, void 0));
        /**
         * Sender email address (envelope from)
         */
        from = (__runInitializers(this, _messageId_extraInitializers), __runInitializers(this, _from_initializers, void 0));
        /**
         * Recipient email addresses
         */
        to = (__runInitializers(this, _from_extraInitializers), __runInitializers(this, _to_initializers, void 0));
        /**
         * CC recipients
         */
        cc = (__runInitializers(this, _to_extraInitializers), __runInitializers(this, _cc_initializers, void 0));
        /**
         * BCC recipients
         */
        bcc = (__runInitializers(this, _cc_extraInitializers), __runInitializers(this, _bcc_initializers, void 0));
        /**
         * Email subject
         */
        subject = (__runInitializers(this, _bcc_extraInitializers), __runInitializers(this, _subject_initializers, void 0));
        /**
         * Raw RFC822 email content
         */
        rawContent = (__runInitializers(this, _subject_extraInitializers), __runInitializers(this, _rawContent_initializers, void 0));
        /**
         * Current status of the email
         */
        status = (__runInitializers(this, _rawContent_extraInitializers), __runInitializers(this, _status_initializers, void 0));
        /**
         * Number of delivery attempts
         */
        attempts = (__runInitializers(this, _status_extraInitializers), __runInitializers(this, _attempts_initializers, 0));
        /**
         * Maximum number of delivery attempts
         */
        maxAttempts = (__runInitializers(this, _attempts_extraInitializers), __runInitializers(this, _maxAttempts_initializers, 3));
        /**
         * Timestamp for next delivery attempt
         */
        nextAttempt = (__runInitializers(this, _maxAttempts_extraInitializers), __runInitializers(this, _nextAttempt_initializers, void 0));
        /**
         * Last error message if delivery failed
         */
        lastError = (__runInitializers(this, _nextAttempt_extraInitializers), __runInitializers(this, _lastError_initializers, void 0));
        /**
         * Timestamp when the email was successfully delivered
         */
        deliveredAt = (__runInitializers(this, _lastError_extraInitializers), __runInitializers(this, _deliveredAt_initializers, void 0));
        /**
         * Sender domain (for querying/filtering)
         */
        senderDomain = (__runInitializers(this, _deliveredAt_extraInitializers), __runInitializers(this, _senderDomain_initializers, void 0));
        /**
         * Priority level (higher = more important)
         */
        priority = (__runInitializers(this, _senderDomain_extraInitializers), __runInitializers(this, _priority_initializers, 0));
        /**
         * JSON-serialized route data
         */
        routeData = (__runInitializers(this, _priority_extraInitializers), __runInitializers(this, _routeData_initializers, void 0));
        /**
         * DKIM signature status
         */
        dkimSigned = (__runInitializers(this, _routeData_extraInitializers), __runInitializers(this, _dkimSigned_initializers, false));
        constructor() {
            super();
            __runInitializers(this, _dkimSigned_extraInitializers);
            this.setTTL(TTL.DAYS_30); // Default 30-day TTL
            this.status = 'pending';
            this.to = [];
            this.cc = [];
            this.bcc = [];
        }
        /**
         * Create a new CachedEmail with a unique ID
         */
        static createNew() {
            const email = new CachedEmail();
            email.id = plugins.uuid.v4();
            return email;
        }
        /**
         * Find an email by ID
         */
        static async findById(id) {
            return await CachedEmail.getInstance({
                id,
            });
        }
        /**
         * Find all emails with a specific status
         */
        static async findByStatus(status) {
            return await CachedEmail.getInstances({
                status,
            });
        }
        /**
         * Find all emails pending delivery (status = pending and nextAttempt <= now)
         */
        static async findPendingForDelivery(limit = 25) {
            const now = new Date();
            return await CachedEmail.findLimited({
                status: { $in: ['pending', 'deferred', 'processing'] },
                nextAttempt: { $lte: now },
            }, limit);
        }
        static async findQueuedForRecovery(limit = 25) {
            return await CachedEmail.findLimited({
                status: 'queued',
            }, limit);
        }
        static async findLimited(filter, limit) {
            const safeLimit = Number.isFinite(limit) ? Math.max(0, Math.floor(limit)) : 25;
            if (safeLimit === 0) {
                return [];
            }
            const collection = CachedEmail.collection;
            const cursor = await collection.getCursor(filter, CachedEmail);
            cursor.mongodbCursor.limit(safeLimit);
            try {
                return await cursor.toArray();
            }
            finally {
                await cursor.close();
            }
        }
        /**
         * Find emails by sender domain
         */
        static async findBySenderDomain(domain) {
            return await CachedEmail.getInstances({
                senderDomain: domain,
            });
        }
        /**
         * Mark as delivered
         */
        markDelivered() {
            this.status = 'delivered';
            this.deliveredAt = new Date();
        }
        /**
         * Mark as failed with error
         */
        markFailed(error) {
            this.status = 'failed';
            this.lastError = error;
        }
        /**
         * Increment attempt counter and schedule next attempt
         */
        scheduleRetry(delayMs = 5 * 60 * 1000) {
            this.attempts++;
            this.status = 'deferred';
            this.nextAttempt = new Date(Date.now() + delayMs);
            // If max attempts reached, mark as failed
            if (this.attempts >= this.maxAttempts) {
                this.status = 'failed';
                this.lastError = `Max attempts (${this.maxAttempts}) reached`;
            }
        }
        /**
         * Extract sender domain from email address
         */
        updateSenderDomain() {
            if (this.from) {
                const match = this.from.match(/@([^>]+)>?$/);
                if (match) {
                    this.senderDomain = match[1].toLowerCase();
                }
            }
        }
    };
    return CachedEmail = _classThis;
})();
export { CachedEmail };
//# sourceMappingURL=data:application/json;base64, 