import { fetchKdocsStatus } from '../api/kdocs'

const CACHE_KEY = 'admin:kdocs:status:v1'
const DEFAULT_MAX_AGE_MS = 5 * 60 * 1000

let memoryStatus = null
let memoryUpdatedAt = 0
let inflightPromise = null

function nowTs() {
  return Date.now()
}

function normalizeStatus(raw) {
  if (!raw || typeof raw !== 'object') return {}
  return raw
}

function readSessionCache() {
  try {
    const raw = window.sessionStorage.getItem(CACHE_KEY)
    if (!raw) return null
    const parsed = JSON.parse(raw)
    if (!parsed || typeof parsed !== 'object') return null
    const updatedAt = Number(parsed.updated_at || 0)
    const status = normalizeStatus(parsed.status)
    if (!updatedAt) return null
    return { status, updatedAt }
  } catch {
    return null
  }
}

function writeSessionCache(status, updatedAt) {
  try {
    window.sessionStorage.setItem(
      CACHE_KEY,
      JSON.stringify({
        status: normalizeStatus(status),
        updated_at: Number(updatedAt || nowTs()),
      }),
    )
  } catch {
    // ignore
  }
}

function hydrateFromSessionIfNeeded() {
  if (memoryStatus !== null) return
  const cached = readSessionCache()
  if (!cached) return
  memoryStatus = cached.status
  memoryUpdatedAt = cached.updatedAt
}

function commitStatus(status) {
  memoryStatus = normalizeStatus(status)
  memoryUpdatedAt = nowTs()
  writeSessionCache(memoryStatus, memoryUpdatedAt)
  return memoryStatus
}

function isFresh(maxAgeMs) {
  if (memoryStatus === null || !memoryUpdatedAt) return false
  const ageLimit = Number(maxAgeMs)
  if (!Number.isFinite(ageLimit) || ageLimit < 0) return true
  return nowTs() - memoryUpdatedAt <= ageLimit
}

export function getCachedKdocsStatus(options = {}) {
  hydrateFromSessionIfNeeded()
  const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS
  if (!isFresh(maxAgeMs)) return null
  return normalizeStatus(memoryStatus)
}

export function updateCachedKdocsStatus(status) {
  return commitStatus(status)
}

export function clearCachedKdocsStatus() {
  memoryStatus = null
  memoryUpdatedAt = 0
  inflightPromise = null
  try {
    window.sessionStorage.removeItem(CACHE_KEY)
  } catch {
    // ignore
  }
}

export async function preloadKdocsStatus(options = {}) {
  const {
    force = false,
    maxAgeMs = DEFAULT_MAX_AGE_MS,
    silent = true,
    live = 0,
  } = options

  if (!force) {
    const cached = getCachedKdocsStatus({ maxAgeMs })
    if (cached) return cached
  }

  if (inflightPromise) return inflightPromise

  const params = live ? { live: 1 } : {}
  const requestConfig = {
    __silent: Boolean(silent),
    __no_retry: true,
    timeout: 8000,
  }

  inflightPromise = fetchKdocsStatus(params, requestConfig)
    .then((status) => commitStatus(status || {}))
    .finally(() => {
      inflightPromise = null
    })

  return inflightPromise
}
