import { Log } from "../utils/log.js";
import { Redis, type RedisOptions } from "ioredis";

export {
  Redis,
  Cluster,
  type Callback,
  type RedisOptions,
  type Result,
  type RedisCommander,
} from "ioredis";

const defaultOptions: Partial<RedisOptions> = {
  retryStrategy: (times: number) => {
    const delay = Math.min(times * 50, 1000);
    return delay;
  },
  maxRetriesPerRequest: 20,
};

const logger = Log.create({ namespace: "redis" });

export namespace RedisClient {
  export function create(
    options: RedisOptions,
    handlers?: { onError?: (err: Error) => void },
  ) {
    const client = new Redis({
      ...defaultOptions,
      ...options,
    });

    client.on("error", (error) => {
      if (handlers?.onError) {
        handlers.onError(error);
      } else {
        logger.error(
          new Error(
            `Redis client error:${error} at keyPrefix:${options.keyPrefix}`,
          ),
        );
      }
    });

    return client;
  }
}
