import { getBullMQSafeQueueName } from '../../../src/index.js';
import { Worker } from 'bullmq';
import { createRedisConnection } from './connection.js';
export const createWorker = (queueName, processor, redisConfig, metrics) => {
    const connection = createRedisConnection(redisConfig);
    const prefix = getBullMQSafeQueueName();
    const worker = new Worker(queueName, processor, {
        connection: connection,
        prefix,
    });
    const onCompleted = async (job) => {
        await metrics.recordJob(queueName, 'completed', job);
    };
    const onFailed = async (job, err) => {
        if (job) {
            await metrics.recordJob(queueName, 'failed', job, err);
        }
    };
    worker.on('completed', onCompleted);
    worker.on('failed', onFailed);
    const close = async () => {
        worker.off('completed', onCompleted);
        worker.off('failed', onFailed);
        await worker.close();
        if (typeof connection.quit === 'function') {
            await connection.quit();
        }
        else if (typeof connection.disconnect === 'function') {
            connection.disconnect();
        }
    };
    return Object.freeze({
        close,
    });
};
