"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const chai_1 = require("chai");
const sinon = __importStar(require("sinon"));
const events_1 = require("events");
const sync_1 = require("../../../../src/modules/bitcoin/sync");
const unit_1 = require("../../../helpers/unit");
describe('UtxoMultiThreadSync', function () {
    const sandbox = sinon.createSandbox();
    const chain = 'BTC';
    const network = 'regtest';
    before(unit_1.unitBeforeHelper);
    after(unit_1.unitAfterHelper);
    afterEach(() => sandbox.restore());
    function createSync(overrides = {}) {
        const processOrder = [];
        const config = {
            rpc: { host: 'localhost', port: 8332, username: 'test', password: 'test' },
            threads: 2,
            ...overrides
        };
        const callbacks = {
            getHeaders: sandbox.stub().resolves([]),
            processBlock: sandbox.stub().callsFake(async (block) => {
                processOrder.push(block.hash || 'unknown');
                await new Promise(r => setTimeout(r, 5));
            }),
            getLocalTip: sandbox.stub().resolves({ height: 100 }),
            deserializeBlock: sandbox.stub().callsFake((rawHex) => ({
                hash: rawHex.substring(0, 8),
                header: { toObject: () => ({ hash: rawHex.substring(0, 8), prevHash: '', time: Date.now() / 1000 }) },
                transactions: []
            }))
        };
        const sync = new sync_1.UtxoMultiThreadSync({ chain, network, config, callbacks });
        return { sync, callbacks, processOrder };
    }
    describe('ordered block processing', function () {
        it('should process blocks in height order even when received out of order', async function () {
            const { sync, callbacks, processOrder } = createSync();
            const headers = [
                { hash: 'aaa' },
                { hash: 'bbb' },
                { hash: 'ccc' }
            ];
            let headerCallCount = 0;
            callbacks.getHeaders.callsFake(async () => {
                headerCallCount++;
                return headerCallCount === 1 ? headers : [];
            });
            // Mock worker threads: override getWorkerThread to create fake threads
            const fakeThreads = [];
            sandbox.stub(sync, 'getWorkerThread').callsFake(() => {
                const fakeThread = new events_1.EventEmitter();
                fakeThread.threadId = fakeThreads.length + 1;
                fakeThread.postMessage = sandbox.stub().callsFake((msg) => {
                    if (msg.message === 'start') {
                        setTimeout(() => fakeThread.emit('message', { message: 'ready' }), 5);
                    }
                    else if (msg.message === 'shutdown') {
                        // no-op
                    }
                    else {
                        // Simulate fetching with varying delay — blocks arrive out of order
                        const delay = msg.hash === 'aaa' ? 60 : msg.hash === 'bbb' ? 10 : 30;
                        setTimeout(() => {
                            fakeThread.emit('message', {
                                message: 'sync',
                                hash: msg.hash,
                                height: msg.height,
                                rawBlock: msg.hash + '00000000', // fake raw hex
                                threadId: fakeThread.threadId
                            });
                        }, delay);
                    }
                });
                fakeThreads.push(fakeThread);
                return fakeThread;
            });
            await sync.sync();
            // Even though bbb (height 102) arrives first and ccc (103) arrives second,
            // processing should be in order: aaa (101), bbb (102), ccc (103)
            (0, chai_1.expect)(processOrder).to.deep.equal(['aaa00000', 'bbb00000', 'ccc00000']);
        });
    });
    describe('thread management', function () {
        it('should initialize the configured number of threads', async function () {
            const { sync, callbacks } = createSync({ threads: 3 });
            callbacks.getHeaders.resolves([]);
            const threads = [];
            sandbox.stub(sync, 'getWorkerThread').callsFake(() => {
                const fakeThread = new events_1.EventEmitter();
                fakeThread.threadId = threads.length + 1;
                fakeThread.postMessage = sandbox.stub().callsFake((msg) => {
                    if (msg.message === 'start') {
                        setTimeout(() => fakeThread.emit('message', { message: 'ready' }), 5);
                    }
                });
                threads.push(fakeThread);
                return fakeThread;
            });
            await sync.sync();
            (0, chai_1.expect)(threads.length).to.equal(3);
        });
        it('should emit INITIALSYNCDONE when sync completes', async function () {
            const { sync, callbacks } = createSync();
            let syncDone = false;
            sync.once('INITIALSYNCDONE', () => { syncDone = true; });
            callbacks.getHeaders.resolves([]);
            sandbox.stub(sync, 'getWorkerThread').callsFake(() => {
                const fakeThread = new events_1.EventEmitter();
                fakeThread.threadId = 1;
                fakeThread.postMessage = sandbox.stub().callsFake((msg) => {
                    if (msg.message === 'start') {
                        setTimeout(() => fakeThread.emit('message', { message: 'ready' }), 5);
                    }
                });
                return fakeThread;
            });
            await sync.sync();
            (0, chai_1.expect)(syncDone).to.equal(true);
        });
    });
});
//# sourceMappingURL=sync.test.js.map