import { appConfig } from '../../config/app.js';
import { Logger } from '../../config/logger.js';
/**
 * Redis Key Management Utility
 *
 * Centralizes Redis key prefixing using appConfigObj.prefix
 * to prevent key collisions across different applications/environments
 */
const PREFIX = appConfig.prefix;
/**
 * Creates a prefixed Redis key
 * @param key - Original key name
 * @returns Prefixed key in format: {prefix}-{key}
 */
export function createRedisKey(key) {
    if (!key) {
        Logger.warn('RedisKeyManager: Empty key provided');
        return PREFIX;
    }
    // Remove leading/trailing colons and ensure proper format
    // Using safe string operations instead of regex to prevent ReDoS
    let cleanKey = key;
    while (cleanKey.startsWith(':')) {
        cleanKey = cleanKey.slice(1);
    }
    while (cleanKey.endsWith(':')) {
        cleanKey = cleanKey.slice(0, -1);
    }
    return `${PREFIX}:${cleanKey}`;
}
/**
 * Plain-object Redis Key Manager
 * Uses module-scoped lazy variables and plain functions (no classes)
 */
// Lazy cache for prefixes
let _metricsPrefix;
let _healthPrefix;
let _workerPrefix;
let _queuePrefix;
let _bullmqPrefix;
let _queueLockPrefix;
let _cachePrefix;
let _sessionPrefix;
let _csrfPrefix;
const getMetricsPrefix = () => {
    _metricsPrefix ??= `${PREFIX}_metrics:`;
    return _metricsPrefix;
};
const getHealthPrefix = () => {
    _healthPrefix ??= `${PREFIX}_health:`;
    return _healthPrefix;
};
const getWorkerPrefix = () => {
    _workerPrefix ??= `${PREFIX}_worker:`;
    return _workerPrefix;
};
const getQueuePrefix = () => {
    _queuePrefix ??= `${PREFIX}_queue:`;
    return _queuePrefix;
};
const getBullmqPrefix = () => {
    _bullmqPrefix ??= `${PREFIX}_bull:`;
    return _bullmqPrefix;
};
const getQueueLockPrefix = () => {
    _queueLockPrefix ??= `${PREFIX}_lock:`;
    return _queueLockPrefix;
};
const getCachePrefix = () => {
    _cachePrefix ??= `${PREFIX}_cache:`;
    return _cachePrefix;
};
const getSessionPrefix = () => {
    _sessionPrefix ??= `${PREFIX}_session:`;
    return _sessionPrefix;
};
const getCsrfPrefix = () => {
    _csrfPrefix ??= `${PREFIX}_csrf:`;
    return _csrfPrefix;
};
export const RedisKeys = Object.freeze({
    get metricsPrefix() {
        return getMetricsPrefix();
    },
    get healthPrefix() {
        return getHealthPrefix();
    },
    get workerPrefix() {
        return getWorkerPrefix();
    },
    get queuePrefix() {
        return getQueuePrefix();
    },
    get bullmqPrefix() {
        return getBullmqPrefix();
    },
    get queueLockPrefix() {
        return getQueueLockPrefix();
    },
    get cachePrefix() {
        return getCachePrefix();
    },
    get sessionPrefix() {
        return getSessionPrefix();
    },
    get csrfPrefix() {
        return getCsrfPrefix();
    },
    getCsrfPrefix() {
        return getCsrfPrefix();
    },
    createMetricsKey(workerName, metricType, granularity) {
        return `${getMetricsPrefix()}${workerName}:${metricType}:${granularity}`;
    },
    createHealthKey(workerName) {
        return `${getHealthPrefix()}${workerName}`;
    },
    createWorkerKey(workerName) {
        return `${getWorkerPrefix()}${workerName}`;
    },
    createQueueKey(queueName) {
        return `${getQueuePrefix()}${queueName}`;
    },
    createBullMQKey(queueName) {
        return `${getBullmqPrefix()}${queueName}`;
    },
    createQueueLockKey(lockName) {
        return `${getQueueLockPrefix()}${lockName}`;
    },
    createCacheKey(cacheKey) {
        return `${getCachePrefix()}${cacheKey}`;
    },
    createSessionKey(sessionId) {
        return `${getSessionPrefix()}${sessionId}`;
    },
    createCsrfKey(sessionId) {
        return `${getCsrfPrefix()}${sessionId}`;
    },
    reset() {
        _metricsPrefix = undefined;
        _healthPrefix = undefined;
        _workerPrefix = undefined;
        _queuePrefix = undefined;
        _bullmqPrefix = undefined;
        _queueLockPrefix = undefined;
        _cachePrefix = undefined;
        _sessionPrefix = undefined;
        _csrfPrefix = undefined;
    },
});
// Note: Legacy helpers removed. Use `RedisKeys` APIs directly.
/**
 * Extracts original key from prefixed key
 * @param prefixedKey - Full prefixed key
 * @returns Original key without prefix
 */
export function extractOriginalKey(prefixedKey) {
    if (!prefixedKey.startsWith(`${PREFIX}:`)) {
        return prefixedKey;
    }
    return prefixedKey.substring(`${PREFIX}:`.length);
}
/**
 * Checks if a key belongs to this application
 * @param key - Redis key to check
 * @returns True if key belongs to this application
 */
export function isAppKey(key) {
    return key.startsWith(`${PREFIX}:`);
}
/**
 * Gets the current prefix
 * @returns Current application prefix
 */
export function getPrefix() {
    return PREFIX;
}
export const getBullMQSafeQueueName = () => {
    return PREFIX;
};
/**
 * Creates a prefixed key based on type (legacy function)
 * @deprecated Use RedisKeys methods directly
 * @param type - Type of key
 * @param key - Original key
 * @returns Prefixed key
 */
export function createKeyByType(type, key) {
    switch (type) {
        case 'queue':
            return RedisKeys.createQueueKey(key);
        case 'bullmq':
            return RedisKeys.createBullMQKey(key);
        case 'worker':
            return RedisKeys.createWorkerKey(key);
        case 'session':
            return RedisKeys.createSessionKey(key);
        case 'cache':
            return RedisKeys.createCacheKey(key);
        case 'custom':
            return createRedisKey(key);
        default:
            return createRedisKey(key);
    }
}
