export const cacheLogger = {
  async debug(message: string, ...args: unknown[]): Promise<void> {
    console.debug(`${await loggerPrefix()} ${message}`, ...args)
  },
  async warn(message: string, ...args: unknown[]): Promise<void> {
    console.warn(`${await loggerPrefix()} Warning - ${message}`, ...args)
  },
  async error(message: string, ...args: unknown[]): Promise<void> {
    console.error(`${await loggerPrefix()} Error - ${message}`, ...args)
  },
}

async function loggerPrefix() {
  const instancePrefix = await getCachePrefix()
  return `[Cache] ${instancePrefix ?? ""}`.trim()
}

async function getCachePrefix() {
  const cacheCreated = await isPromiseResolved(global.cacheClient)

  if (!cacheCreated.resolved) {
    return null
  }

  const instanceType = cacheCreated.value?.type
  if (!instanceType) {
    return null
  }

  return `[${instanceType}]`
}

function isPromiseResolved<T>(promise: Promise<T> | undefined) {
  if (!promise) {
    return { resolved: false, value: undefined }
  }

  const check = Promise.race([promise, Promise.resolve("__PENDING__")])

  return check.then((result) => ({
    resolved: result !== "__PENDING__",
    value: result !== "__PENDING__" ? (result as Awaited<T>) : undefined,
  }))
}
