import createStableHash from "@racletteCore/lib/createStableHash"
import { $store } from "@racletteCore"
import log from "@racletteCore/lib/logger"

const isParentResultFresh = (cacheKey: string, ttl: number = 1000): boolean => {
  const queriesState = $store.getState("queriesCache")
  const currentTimeStamp = new Date().getTime()
  const parentQuery = queriesState[cacheKey]

  if (
    !parentQuery.lastFetched ||
    !parentQuery.uuids ||
    parentQuery.hasOwnProperty("loading") === false ||
    parentQuery.loading === true
  ) {
    log.store(
      "queryCacheHelper",
      `cache #${cacheKey} has not been executed yet or is still fetching`,
      parentQuery,
    )
    return false
  }

  const isParentResultFresh = parentQuery.lastFetched + ttl >= currentTimeStamp

  log.store(
    "queryCacheHelper",
    `cache #${cacheKey} is ${isParentResultFresh ? "fresh" : "stale"} for ttl of ${ttl}ms`,
  )

  return isParentResultFresh
}

const getParentActionIdHash = (
  target: string,
  params: Record<string, any>,
): string => {
  return createStableHash({
    target,
    params,
  })
}

const getCacheQueryAndHash = (
  target: string,
  params: Record<string, any>,
): { query: Record<string, any> | undefined; hash: string } => {
  const hash = getParentActionIdHash(target, params)
  const state = $store.getState("queriesCache")
  return {
    query: state[hash],
    hash,
  }
}

const hasCacheQuery = (
  target: string,
  params: Record<string, any>,
): boolean => {
  const cacheQuery = getCacheQueryAndHash(target, params).query
  return !!cacheQuery
}

export {
  getCacheQueryAndHash,
  hasCacheQuery,
  getParentActionIdHash,
  isParentResultFresh,
}
