"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 BlocksQueueService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlocksQueueService = void 0;
const common_1 = require("@nestjs/common");
const blocks_queue_1 = require("./blocks-queue");
const blockchain_provider_1 = require("../blockchain-provider");
let BlocksQueueService = BlocksQueueService_1 = class BlocksQueueService {
    blocksQueueIterator;
    blocksQueueLoader;
    mempoolService;
    blockchainProvider;
    config;
    logger = new common_1.Logger(BlocksQueueService_1.name);
    moduleName = 'blocks-queue';
    _queue;
    constructor(blocksQueueIterator, blocksQueueLoader, mempoolService, blockchainProvider, config) {
        this.blocksQueueIterator = blocksQueueIterator;
        this.blocksQueueLoader = blocksQueueLoader;
        this.mempoolService = mempoolService;
        this.blockchainProvider = blockchainProvider;
        this.config = config;
    }
    onModuleInit() {
        this.logger.verbose('Blocks queue service initialized', { module: this.moduleName });
    }
    get queue() {
        return this._queue;
    }
    async start(indexedHeight) {
        this.initQueue(indexedHeight);
        this.blocksQueueLoader.startBlocksLoading(this._queue);
        this.blocksQueueIterator.startQueueIterating(this._queue);
        this.logger.verbose('Blocks queue service started', { module: this.moduleName, args: { indexedHeight } });
    }
    initQueue(indexedHeight) {
        this._queue = new blocks_queue_1.BlocksQueue({
            lastHeight: Number(indexedHeight),
            maxQueueSize: this.config.maxQueueSize,
            maxBlockHeight: this.config.maxBlockHeight,
            blockSize: this.config.blockSize,
        });
        this.logger.verbose('Blocks queue initialized', {
            module: this.moduleName,
            args: {
                indexedHeight,
                maxQueueSize: this.config.maxQueueSize,
                maxBlockHeight: this.config.maxBlockHeight,
                blockSize: this.config.blockSize,
            },
        });
    }
    async reorganizeBlocks(newStartHeight) {
        this.logger.verbose('Reorganizing blocks', { module: this.moduleName, args: { newStartHeight } });
        try {
            await this._queue.reorganize(Number(newStartHeight));
            await this.mempoolService.refresh(Number(newStartHeight));
        }
        catch (error) {
            this.logger.verbose('Queue reorganization failed', {
                module: this.moduleName,
                args: { newStartHeight, error },
            });
        }
        finally {
            this.blocksQueueIterator.resolveNextBatch();
        }
    }
    async confirmProcessedBatch(blockHashes) {
        this.logger.verbose('Confirming processed batch', { module: this.moduleName, args: { count: blockHashes.length } });
        try {
            const lastBlockHeight = await this._queue.dequeue(blockHashes);
            await this.mempoolService.refresh(lastBlockHeight);
        }
        catch (e) {
            this.logger.verbose('Processed batch confirmation failed', {
                module: this.moduleName,
                args: { count: blockHashes.length, error: e },
            });
        }
        finally {
            this.blocksQueueIterator.resolveNextBatch();
        }
    }
    async getBlocksByHashes(hashes) {
        const hashSet = new Set(hashes);
        const rawBlocks = await this._queue.findBlocks(hashSet);
        return Promise.all(rawBlocks
            .filter(Boolean)
            .map((raw) => this.blockchainProvider.parseBlock(raw.bytes, raw.height, this.config.verifyTrie ?? false)));
    }
};
exports.BlocksQueueService = BlocksQueueService;
exports.BlocksQueueService = BlocksQueueService = BlocksQueueService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [Function, Function, Function, blockchain_provider_1.BlockchainProviderService, Object])
], BlocksQueueService);
