'use strict';

class WorkerPool {
  constructor(concurrency = 8) {
    this.concurrency = Math.max(1, concurrency);
  }

  async run(items, fn, onProgress) {
    const results = new Array(items.length);
    let nextIdx = 0;
    let completed = 0;
    const worker = async () => {
      while (nextIdx < items.length) {
        const idx = nextIdx++;
        try {
          results[idx] = await fn(items[idx], idx);
        } catch (err) {
          results[idx] = { error: err.message };
        }
        completed++;
        if (onProgress) onProgress(completed, items.length);
      }
    };
    const workers = [];
    for (let i = 0; i < this.concurrency; i++) workers.push(worker());
    await Promise.all(workers);
    return results;
  }
}

module.exports = { WorkerPool };
