const LOGIN_ENTRY_TRANSITION_KEY = 'x-financial-login-entry-transition'
const LOGIN_ENTRY_TRANSITION_MAX_AGE_MS = 5000

function canUseSessionStorage() {
  return typeof window !== 'undefined' && typeof window.sessionStorage !== 'undefined'
}

export function markLoginEntryTransition() {
  if (!canUseSessionStorage()) {
    return
  }

  window.sessionStorage.setItem(LOGIN_ENTRY_TRANSITION_KEY, String(Date.now()))
}

export function consumeLoginEntryTransition() {
  if (!canUseSessionStorage()) {
    return false
  }

  const rawTimestamp = window.sessionStorage.getItem(LOGIN_ENTRY_TRANSITION_KEY)
  window.sessionStorage.removeItem(LOGIN_ENTRY_TRANSITION_KEY)

  if (!rawTimestamp) {
    return false
  }

  const timestamp = Number(rawTimestamp)

  if (!Number.isFinite(timestamp)) {
    return true
  }

  return Date.now() - timestamp <= LOGIN_ENTRY_TRANSITION_MAX_AGE_MS
}
