export const ACCESS_TOKEN_STORAGE_KEY = 'th_hotel_access_token'

let memoryAccessToken: string | null = null

export function getStoredAccessToken(): string | null {
  const storage = getSessionStorage()
  if (!storage) {
    return memoryAccessToken
  }
  return storage.getItem(ACCESS_TOKEN_STORAGE_KEY)
}

export function setStoredAccessToken(token: string): void {
  memoryAccessToken = token
  getSessionStorage()?.setItem(ACCESS_TOKEN_STORAGE_KEY, token)
}

export function clearStoredAccessToken(): void {
  memoryAccessToken = null
  getSessionStorage()?.removeItem(ACCESS_TOKEN_STORAGE_KEY)
}

function getSessionStorage(): Storage | null {
  if (typeof window === 'undefined') {
    return null
  }
  return window.sessionStorage
}
