const regChallenges = globalThis.__HTC_WEBAUTHN_REG_CHALLENGES__ || new Map()
const authChallenges = globalThis.__HTC_WEBAUTHN_AUTH_CHALLENGES__ || new Map()
const preRegChallenges = globalThis.__HTC_WEBAUTHN_PRE_REG__ || new Map()
globalThis.__HTC_WEBAUTHN_REG_CHALLENGES__ = regChallenges
globalThis.__HTC_WEBAUTHN_AUTH_CHALLENGES__ = authChallenges
globalThis.__HTC_WEBAUTHN_PRE_REG__ = preRegChallenges

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

function cleanup(map) {
  const now = nowMs()
  for (const [k, v] of map.entries()) {
    if (!v || !v.expiresAt || v.expiresAt <= now) map.delete(k)
  }
}

export function setRegistrationChallenge(userId, challenge, ttlMs = 5 * 60 * 1000) {
  cleanup(regChallenges)
  regChallenges.set(String(userId), { challenge, expiresAt: nowMs() + ttlMs })
}

export function getRegistrationChallenge(userId) {
  cleanup(regChallenges)
  const v = regChallenges.get(String(userId))
  return v?.challenge || null
}

export function clearRegistrationChallenge(userId) {
  regChallenges.delete(String(userId))
}

export function setAuthChallenge(challenge, ttlMs = 5 * 60 * 1000) {
  cleanup(authChallenges)
  authChallenges.set(String(challenge), { expiresAt: nowMs() + ttlMs })
}

export function consumeAuthChallenge(challenge) {
  cleanup(authChallenges)
  const key = String(challenge)
  const v = authChallenges.get(key)
  if (!v) return false
  authChallenges.delete(key)
  return true
}

export function setPreRegistration(registrationId, payload, ttlMs = 10 * 60 * 1000) {
  cleanup(preRegChallenges)
  preRegChallenges.set(String(registrationId), { payload, expiresAt: nowMs() + ttlMs })
}

export function consumePreRegistration(registrationId) {
  cleanup(preRegChallenges)
  const key = String(registrationId)
  const v = preRegChallenges.get(key)
  if (!v) return null
  preRegChallenges.delete(key)
  return v.payload || null
}

export function getPreRegistration(registrationId) {
  cleanup(preRegChallenges)
  const key = String(registrationId)
  const v = preRegChallenges.get(key)
  if (!v) return null
  return v.payload || null
}


