import { env } from "@/env/server"

import { isEdge } from "@/utils/isEdge"

import { createMemoryCache } from "./MemoryCache/createMemoryCache"
import { type DataCache } from "./Cache"
import { createDistributedCache } from "./DistributedCache"
import { cacheLogger } from "./logger"

export type { CacheTime, DataCache } from "./Cache"

export async function getCacheClient(): Promise<DataCache> {
  if (global.cacheClient) {
    return global.cacheClient
  }

  global.cacheClient = env.REDIS_API_HOST
    ? createDistributedCache()
    : createMemoryCache()

  const cacheClient = await global.cacheClient
  cacheLogger.debug(
    `Creating ${cacheClient.type} cache on ${isEdge ? "edge" : "server"} runtime`
  )

  return global.cacheClient
}
