import { createClient, RedisClient } from "redis";
import { error } from "console";

export const createRedisClient = (): RedisClient => {
  if (
    !process.env.REDIS_HOST ||
    !process.env.REDIS_PORT ||
    !process.env.REDIS_PASSWORD
  ) {
    throw error("Required environment variables are not set.");
  }

  const host = process.env.REDIS_HOST;
  const port = parseInt(process.env.REDIS_PORT, 10);
  const password = process.env.REDIS_PASSWORD;

  let client: RedisClient;
  if (process.env.STAGE === "local") {
    client = createClient({
      host: host,
      port: port,
      password: password,
      retry_strategy: (options) => {
        if (options.attempt <= 3) {
          console.log(
            `Retrying connection to Redis. Attempt ${options.attempt}`
          );
          return 10000; // ミリ秒単位でのリトライまでの間隔
        } else {
          console.log("Exceeded maximum number of connection attempts.");
          return undefined; // リトライを終了
        }
      },
    });
  } else {
    client = createClient({
      url: `rediss://${host}:${port}`,
      password: password,
      tls: {},
      retry_strategy: (options) => {
        if (options.attempt <= 3) {
          console.log(
            `Retrying connection to Redis. Attempt ${options.attempt}`
          );
          return 10000; // ミリ秒単位でのリトライまでの間隔
        } else {
          console.log("Exceeded maximum number of connection attempts.");
          return undefined; // リトライを終了
        }
      },
    });
  }

  client.on("error", (err) => console.log("Redis Client Error", err));

  return client;
};
