import type { CacheLogFn, CacheStore } from "./redis-cache";
import {
  createRedisCache,
  resolveDefaultTtlSecondsFromEnv,
  resolveRedisUrlFromEnv,
} from "./redis-cache";
import { createNoopCache } from "./noop-cache";

export async function createCacheFromEnv(
  env: NodeJS.ProcessEnv,
  opts?: { namespace?: string; log?: CacheLogFn },
): Promise<CacheStore> {
  const url = resolveRedisUrlFromEnv(env);
  if (!url) return createNoopCache(opts?.log);

  try {
    return await createRedisCache({
      url,
      defaultTtlSeconds: resolveDefaultTtlSecondsFromEnv(env),
      namespace: opts?.namespace,
      log: opts?.log,
    });
  } catch (e) {
    opts?.log?.(`cache: disabled (redis connect failed: ${String(e)})`);
    return createNoopCache(opts?.log);
  }
}

