const { Worker } = require('worker_threads');

class WorkerPool {
    constructor(workerScript, numWorkers = 4) {
        this.workers = [];
        this.queue = [];
        this.activeWorkers = new Set();

        for (let i = 0; i < numWorkers; i++) {
            const worker = new Worker(workerScript);
            this.workers.push(worker);
        }
    }

    async execute(data) {
        const worker = await this.getWorker();
        
        try {
            return await new Promise((resolve, reject) => {
                worker.postMessage(data);
                
                worker.once('message', resolve);
                worker.once('error', reject);
            });
        } finally {
            this.releaseWorker(worker);
        }
    }

    async getWorker() {
        const availableWorker = this.workers.find(w => !this.activeWorkers.has(w));
        
        if (availableWorker) {
            this.activeWorkers.add(availableWorker);
            return availableWorker;
        }

        return new Promise(resolve => {
            this.queue.push(resolve);
        });
    }

    releaseWorker(worker) {
        this.activeWorkers.delete(worker);
        
        if (this.queue.length > 0) {
            const resolve = this.queue.shift();
            this.activeWorkers.add(worker);
            resolve(worker);
        }
    }

    terminate() {
        return Promise.all(
            this.workers.map(worker => worker.terminate())
        );
    }
}

module.exports = WorkerPool;