import { logger } from '@goodgo/logger';
import CircuitBreaker from 'opossum';

/**
 * EN: Circuit Breaker Configuration
 * VI: Cấu hình Circuit Breaker
 */
const defaultOptions: CircuitBreaker.Options = {
    timeout: 3000, // 3 seconds
    errorThresholdPercentage: 50,
    resetTimeout: 30000, // 30 seconds
};

/**
 * EN: Create a circuit breaker for an async function
 * VI: Tạo circuit breaker cho một hàm bất đồng bộ
 * 
 * @param action - Async function to protect
 * @param name - Name of the circuit breaker
 * @param options - Override default options
 */
export const createCircuitBreaker = <TArgs extends any[], TResult>(
    action: (...args: TArgs) => Promise<TResult>,
    name: string,
    options: Partial<CircuitBreaker.Options> = {}
): CircuitBreaker<TArgs, TResult> => {
    const breaker = new CircuitBreaker(action, {
        ...defaultOptions,
        ...options,
        name,
    });

    breaker.on('open', () => {
        logger.warn(`Circuit Breaker OPEN: ${name}`);
    });

    breaker.on('halfOpen', () => {
        logger.info(`Circuit Breaker HALF-OPEN: ${name}`);
    });

    breaker.on('close', () => {
        logger.info(`Circuit Breaker CLOSED: ${name}`);
    });

    breaker.on('fallback', () => {
        logger.warn(`Circuit Breaker FALLBACK: ${name}`);
    });

    return breaker;
};
