"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisPublisher = void 0;
const common_1 = require("@nestjs/common");
const ioredis_1 = __importDefault(require("ioredis"));
const uuid_1 = require("uuid");
const common_2 = require("./common");
class RedisPublisher {
    constructor(mqMessageService, mqMessageQueueService) {
        this.mqMessageService = mqMessageService;
        this.mqMessageQueueService = mqMessageQueueService;
        this.logger = new common_1.Logger(RedisPublisher.name);
        this.client = null;
        this.serviceRole = process.env.QUEUES_SERVICE_ROLE || 'both';
        if (!process.env.QUEUES_SERVICE_ROLE) {
            this.logger.debug('QUEUES_SERVICE_ROLE is not defined. Defaulting RedisPublisher service role to "both".');
        }
        if (!process.env.QUEUES_REDIS_URL) {
            this.logger.debug('RedisPublisher: QUEUES_REDIS_URL is not defined in the environment variables');
        }
    }
    getClient() {
        if (!this.client) {
            this.client = new ioredis_1.default(process.env.QUEUES_REDIS_URL);
            this.client.on('error', (err) => {
                this.logger.error(`RedisPublisher connection error: ${err.message}`, err.stack);
            });
        }
        return this.client;
    }
    async onModuleDestroy() {
        if (this.client) {
            await this.client.quit();
            this.client = null;
        }
    }
    async publish(message) {
        if (!process.env.QUEUES_REDIS_URL) {
            throw new Error('RedisPublisher: QUEUES_REDIS_URL is not defined in the environment variables');
        }
        if (!this.serviceRole) {
            throw new Error('RedisPublisher: Queue service Role is not defined in the environment variables');
        }
        if (this.serviceRole === 'subscriber') {
            throw new Error('RedisPublisher: Queue service Role is subscriber, cannot publish messages');
        }
        if (!message.retryCount)
            message.retryCount = 0;
        if (!message.retryInterval)
            message.retryInterval = 1000;
        message.messageId = (0, uuid_1.v4)();
        const queueName = this.options().queueName;
        const namespacedQueueName = (0, common_2.buildNamespacedQueueName)(queueName);
        await this.persistToDatabase(namespacedQueueName, message);
        try {
            const client = this.getClient();
            await client.publish(namespacedQueueName, JSON.stringify(message));
            this.logger.debug(`RedisPublisher published message ${message.messageId} to channel ${namespacedQueueName}`);
        }
        catch (err) {
            this.logger.error(`RedisPublisher failed to publish message: ${err.message}`, err.stack);
        }
        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.RedisPublisher = RedisPublisher;
//# sourceMappingURL=redis-publisher.service.js.map