/**
 * Test Worker
 * Processes jobs from queues using the new Worker Management System
 */
import { Logger } from '../../src/config/logger.js';
import { ErrorFactory } from '../../src/exceptions/ZintrustError.js';
import queueConfig from '../../config/queue.js';
import { HealthMonitor, WorkerFactory } from '../../packages/workers/src/index.js';
const WORKER_NAME = 'test-worker';
let currentQueueName = null;
function createTestWorkerProcessor(queueName) {
    return async (job) => {
        Logger.info(`Processing job ${job.id ?? 'unknown'} from queue ${queueName}`);
        // Simulate processing time (1-3 seconds)
        const processingTime = 1000 + Math.random() * 2000; //NOSONAR
        let _timer;
        try {
            await new Promise((resolve) => {
                // eslint-disable-next-line no-restricted-syntax
                _timer = setTimeout(resolve, processingTime);
            });
        }
        finally {
            if (_timer) {
                clearTimeout(_timer);
            }
        }
        // Check if job should fail
        const data = job.data;
        if (data?.shouldFail === true) {
            Logger.error(`Job ${job.id ?? 'unknown'} is configured to fail`);
            throw ErrorFactory.createValidationError(`Job intentionally failed: ${data.message ?? 'Test failure'}`);
        }
        Logger.info(`Job ${job.id ?? 'unknown'} completed successfully`);
        return { success: true, processedAt: new Date().toISOString() };
    };
}
async function createTestWorker(queueName) {
    // Create worker using the new WorkerFactory with all enterprise features
    await WorkerFactory.create({
        name: WORKER_NAME,
        version: '1.0.0',
        queueName,
        processor: createTestWorkerProcessor(queueName),
        options: {
            connection: {
                host: queueConfig.drivers.redis.host,
                port: queueConfig.drivers.redis.port,
                password: queueConfig.drivers.redis.password ?? undefined,
            },
            concurrency: 5,
            limiter: {
                max: 10,
                duration: 1000,
            },
        },
        features: {
            clustering: true,
            metrics: true,
            autoScaling: false, // Disabled for test worker
            circuitBreaker: true,
            deadLetterQueue: true,
            resourceMonitoring: true,
            compliance: false, // Not needed for test data
            observability: true,
            plugins: true,
            versioning: true,
            datacenterOrchestration: false, // Single datacenter for testing
        },
    });
}
function startTestWorkerMonitoring() {
    // Start health monitoring
    HealthMonitor.startMonitoring(WORKER_NAME, {
        checkInterval: 30,
        thresholds: {
            errorRate: { warning: 0.1, critical: 0.2 }, // More lenient for test worker
            latency: { warning: 2000, critical: 5000 },
            throughput: { warning: 5, critical: 2 },
            cpu: { warning: 80, critical: 95 },
            memory: { warning: 80, critical: 90 },
            queueSize: { warning: 100, critical: 500 },
        },
        alerting: {
            enabled: true,
            degradedCallback: (workerName, result) => {
                Logger.warn(`Worker health degraded: ${workerName}`, {
                    score: result.score,
                    recommendations: result.recommendations,
                });
            },
            criticalCallback: (workerName, result) => {
                Logger.error(`Worker health critical: ${workerName}`, {
                    score: result.score,
                    recommendations: result.recommendations,
                });
            },
        },
    });
}
export async function startTestWorker(queueName) {
    if (currentQueueName !== null) {
        Logger.info('Test worker already running', { currentQueue: currentQueueName });
        return;
    }
    await createTestWorker(queueName);
    startTestWorkerMonitoring();
    currentQueueName = queueName;
    Logger.info(`Test worker started for queue: ${queueName}`, {
        workerName: WORKER_NAME,
        features: 'clustering, metrics, circuit-breaker, dlq, resources, observability, plugins, versioning',
    });
}
export async function stopTestWorker() {
    if (currentQueueName === null) {
        Logger.info('No test worker running');
        return;
    }
    try {
        // Stop health monitoring
        HealthMonitor.stopMonitoring(WORKER_NAME);
        // Stop and remove worker
        await WorkerFactory.stop(WORKER_NAME);
        await WorkerFactory.remove(WORKER_NAME);
        currentQueueName = null;
        Logger.info('Test worker stopped', { workerName: WORKER_NAME });
    }
    catch (error) {
        Logger.error('Failed to stop test worker', error);
        throw error;
    }
}
export function isWorkerRunning() {
    return currentQueueName !== null;
}
/**
 * Get test worker metrics
 */
export async function getTestWorkerMetrics() {
    if (currentQueueName === null) {
        return null;
    }
    return WorkerFactory.getMetrics(WORKER_NAME);
}
/**
 * Get test worker health
 */
export async function getTestWorkerHealth() {
    if (currentQueueName === null) {
        return null;
    }
    return HealthMonitor.getCurrentHealth(WORKER_NAME);
}
