"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DatabasePublisher = void 0;
const common_1 = require("@nestjs/common");
const uuid_1 = require("uuid");
const common_2 = require("./common");
class DatabasePublisher {
    constructor(mqMessageService, mqMessageQueueService) {
        this.mqMessageService = mqMessageService;
        this.mqMessageQueueService = mqMessageQueueService;
        this.logger = new common_1.Logger(DatabasePublisher.name);
        this.serviceRole = process.env.QUEUES_SERVICE_ROLE || 'both';
        if (!process.env.QUEUES_SERVICE_ROLE) {
            this.logger.debug('QUEUES_SERVICE_ROLE is not defined. Defaulting DatabasePublisher service role to "both".');
        }
    }
    async publish(message) {
        if (!this.serviceRole) {
            this.logger.error('Queue service Role is not defined in the environment variables');
            throw new Error('Queue service Role is not defined in the environment variables');
        }
        if (this.serviceRole === 'subscriber') {
            this.logger.error('Queue service Role is subscriber, cannot publish messages');
            throw new Error('Queue service Role is subscriber, cannot publish messages');
        }
        this.logger.debug(`DatabasePublisher publishing with options: ${JSON.stringify(this.options())}`);
        const options = this.options();
        const queueName = options.queueName;
        const namespacedQueueName = (0, common_2.buildNamespacedQueueName)(queueName);
        if (!message.retryCount)
            message.retryCount = 0;
        if (!message.retryInterval)
            message.retryInterval = 1000;
        message.messageId = (0, uuid_1.v4)();
        await this.persistToDatabase(namespacedQueueName, message);
        return message.messageId;
    }
    async persistToDatabase(queueName, message) {
        try {
            const mqMessageQueue = await this.mqMessageQueueService.resolveQueue(queueName);
            await this.mqMessageService.create({
                messageBroker: this.options().type,
                messageId: message.messageId,
                retryCount: message.retryCount,
                retryInterval: message.retryInterval,
                stage: 'pending',
                startedAt: new Date(),
                input: JSON.stringify(message, null, 2),
                parentEntityId: message.parentEntityId,
                parentEntity: message.parentEntity,
                mqMessageQueueId: mqMessageQueue.id,
            });
        }
        catch (error) {
            this.logger.error(error.message, error.stack);
        }
    }
}
exports.DatabasePublisher = DatabasePublisher;
//# sourceMappingURL=database-publisher.service.js.map