import { LocalCache, CacheInstance, RedisCache } from 'cachette';
import crypto from 'crypto';
import Logger from './logger.js';

/**
 * Initializes a Cache backed by the Redis instance at the provided url if present, or a LocalCache otherwise.
 *
 * @param redisUrl - The redis url to connect to (optional).
 * @returns A cache instance.
 */
function create(redisUrl?: string): CacheInstance {
  const cacheInstance: CacheInstance = redisUrl ? new RedisCache(redisUrl) : new LocalCache();

  // Intended: the correlation id will be the same for all logs of Cachette.
  const correlationId = crypto.randomUUID();

  const logger = new Logger({ correlation_id: correlationId });

  cacheInstance
    .on('info', message => {
      logger.info(message);
    })
    .on('warn', message => {
      logger.warn(message);
    })
    .on('error', message => {
      logger.error(message);
    });

  return cacheInstance;
}

export const Cache = { create };
export type { CacheInstance };
