"use strict";
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);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var BlocksQueueIteratorService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlocksQueueIteratorService = void 0;
const uuid_1 = require("uuid");
const common_1 = require("@nestjs/common");
const exponential_interval_async_1 = require("@easylayer/common/exponential-interval-async");
const blockchain_provider_1 = require("../../blockchain-provider");
let BlocksQueueIteratorService = BlocksQueueIteratorService_1 = class BlocksQueueIteratorService {
    blocksCommandExecutor;
    blockchainProvider;
    config;
    log = new common_1.Logger(BlocksQueueIteratorService_1.name);
    _queue;
    _isIterating = false;
    batchProcessedPromise;
    _resolveNextBatch;
    _blocksBatchSize = 1024;
    _timer = null;
    _monitoringInterval;
    constructor(blocksCommandExecutor, blockchainProvider, config) {
        this.blocksCommandExecutor = blocksCommandExecutor;
        this.blockchainProvider = blockchainProvider;
        this.config = config;
        this._blocksBatchSize = this.config.queueIteratorBlocksBatchSize;
        // Calculate monitoring interval once in constructor
        // Half of block time, minimum 30 seconds
        this._monitoringInterval = Math.max(this.config.blockTimeMs / 4, 3000);
        // TODO: This should be removed when we figure out where to initialize the queue correctly.
        // Now, without this line, we can get a situation where the queue is not initialized
        // (method startQueueIterating() is not called),
        // and method _resolveNextBatch() is provided in the getter, which will cause an error.
        this._resolveNextBatch = () => { };
    }
    get resolveNextBatch() {
        return this._resolveNextBatch;
    }
    get isIterating() {
        return this._isIterating;
    }
    onModuleDestroy() {
        this.log.debug('Shutting down iterator');
        this._timer?.destroy();
        this._timer = null;
        this._resolveNextBatch();
        this._isIterating = false;
    }
    /**
     * Starts iterating over the block queue and processing blocks.
     */
    async startQueueIterating(queue) {
        this.log.debug('Start blocks iterating', {
            args: { initialQueueLength: queue.length },
        });
        // NOTE: We use this to make sure that
        // method startQueueIterating() is executed only once in its entire life.
        if (this._isIterating) {
            this.log.debug('Blocks iterating skipped: already iterating');
            // Iterating Blocks already started
            return;
        }
        this._isIterating = true;
        // TODO: think where put this
        this._queue = queue;
        this.log.debug('Queue assigned to iterator', {
            args: { currentSize: this._queue.currentSize },
        });
        this._timer = (0, exponential_interval_async_1.exponentialIntervalAsync)(async (resetInterval) => {
            // IMPORTANT: Before processing the next batch from the queue,
            // we wait for the resolving of the promise of the previous batch (confirm batch method)
            await this.batchProcessedPromise;
            this.log.debug('Previous batch resolved, fetching next batch');
            const batch = await this.peekNextBatch();
            if (batch.length > 0) {
                await this.processBatch(batch);
                this.log.debug('Batch processed, resetting interval');
                resetInterval();
            }
            else {
                this.log.debug('No blocks to process this tick');
            }
        }, {
            interval: 1000, // Start with 1000ms for first attempts
            maxInterval: this._monitoringInterval, // Max interval = monitoring interval (half block time)
            multiplier: 2, // Exponential backoff multiplier
        });
        this.log.debug('Iterator exponential timer started');
    }
    async processBatch(batch) {
        // Init the promise for the next wait
        this.initBatchProcessedPromise();
        this.log.debug('Iterator process batch with length', { args: { batchLength: batch.length } });
        try {
            await this.blocksCommandExecutor.handleBatch({ batch, requestId: (0, uuid_1.v4)() });
            this.log.debug('handleBatch succeeded');
        }
        catch (error) {
            this.log.debug('Failed to process the batch, will retry', {
                methodName: 'processBatch',
                args: error,
            });
            // IMPORTANT: We call this to resolve queue promise
            // that we can try same block one more time
            this._resolveNextBatch();
        }
    }
    /**
     * Retrieves the next batch of blocks for processing.
     *
     * Uses maximum batch size approach to ensure optimal performance:
     * - Always processes available blocks (guarantees progress)
     * - Respects memory limits by not exceeding maximum batch size
     * - Prevents resource starvation by taking all available blocks up to the limit
     *
     * This approach is better than minimum batch size because:
     * - No deadlock when blocks are smaller than minimum threshold
     * - Efficient resource utilization
     * - Predictable performance characteristics
     *
     * @returns Promise resolving to array of blocks ready for processing
     */
    async peekNextBatch() {
        // Maximum batch size in bytes - this is our memory/processing limit
        const maxBatchSize = this._blocksBatchSize;
        // This is a peek: queue-owned payload is released only after confirmProcessedBatch().
        const rawBatch = await this._queue.getBatchUpToSize(maxBatchSize);
        const blocks = [];
        for (const raw of rawBatch) {
            blocks.push(await this.blockchainProvider.parseBlock(raw.bytes, raw.height, this.config.verifyTrie ?? false));
        }
        const batch = blocks;
        this.log.debug('Fetched batch for processing', {
            args: {
                batchLength: batch.length,
                maxBatchSize,
                totalBatchSize: batch.reduce((sum, block) => sum + block.size, 0),
            },
        });
        return batch;
    }
    initBatchProcessedPromise() {
        this.batchProcessedPromise = new Promise((resolve) => {
            this._resolveNextBatch = resolve;
        });
        if (this._queue.length === 0) {
            this._resolveNextBatch();
        }
    }
};
exports.BlocksQueueIteratorService = BlocksQueueIteratorService;
exports.BlocksQueueIteratorService = BlocksQueueIteratorService = BlocksQueueIteratorService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, common_1.Inject)('BlocksCommandExecutor')),
    __metadata("design:paramtypes", [Object, blockchain_provider_1.BlockchainProviderService, Object])
], BlocksQueueIteratorService);
