import { createClient } from "redis";

import { env } from "../config/env.js";

let clientPromise: Promise<ReturnType<typeof createClient> | null> | null = null;

export const getRedis = async (): Promise<ReturnType<typeof createClient> | null> => {
  if (!env.REDIS_URL) {
    return null;
  }

  if (!clientPromise) {
    clientPromise = (async () => {
      const client = createClient({ url: env.REDIS_URL });
      client.on("error", (error) => {
        console.error("redis error", error);
      });
      await client.connect();
      return client;
    })().catch((error) => {
      console.error("redis init failed", error);
      return null;
    });
  }

  return clientPromise;
};
