import { afterEach, describe, expect, it, vi } from 'vitest'

import {
  clearRefreshToken,
  getRefreshToken,
  hasRefreshToken,
  hasSessionPresenceCookie,
  setRefreshToken,
} from './token-storage'

const originalDocument = globalThis.document

describe('token-storage', () => {
  afterEach(() => {
    clearRefreshToken()
    vi.restoreAllMocks()

    Object.defineProperty(globalThis, 'document', {
      configurable: true,
      value: originalDocument,
    })
  })

  it('stores refresh tokens in memory and normalizes empty values to null', () => {
    setRefreshToken('  refresh-token  ')

    expect(getRefreshToken()).toBe('refresh-token')
    expect(hasRefreshToken()).toBe(true)

    setRefreshToken('   ')
    expect(getRefreshToken()).toBeNull()
    expect(hasRefreshToken()).toBe(false)

    setRefreshToken(undefined)
    expect(getRefreshToken()).toBeNull()
  })

  it('clears the in-memory refresh token explicitly', () => {
    setRefreshToken('token-to-clear')
    expect(hasRefreshToken()).toBe(true)

    clearRefreshToken()

    expect(getRefreshToken()).toBeNull()
    expect(hasRefreshToken()).toBe(false)
  })

  it('detects the session presence cookie when it is present among other cookies', () => {
    vi.spyOn(document, 'cookie', 'get').mockReturnValue('foo=bar; ums_session_present=1; theme=dark')

    expect(hasSessionPresenceCookie()).toBe(true)
  })

  it('returns false when the session presence cookie is absent', () => {
    vi.spyOn(document, 'cookie', 'get').mockReturnValue('foo=bar; theme=dark')

    expect(hasSessionPresenceCookie()).toBe(false)
  })

  it('returns false when document is unavailable', () => {
    Object.defineProperty(globalThis, 'document', {
      configurable: true,
      value: undefined,
    })

    expect(hasSessionPresenceCookie()).toBe(false)
  })
})
