import assert from 'node:assert/strict'

import {
  AUTH_ACCESS_TOKEN_KEY,
  AUTH_EXPIRES_AT_KEY,
  buildBearerHeaders,
  clearAuthCredentials,
  hasValidAuthSession,
  persistAuthCredentials,
  readAuthAccessToken,
  readAuthExpiresAt
} from '../src/utils/authSessionStorage.js'

const storage = new Map()
global.window = {
  sessionStorage: {
    getItem(key) {
      return storage.get(key) ?? null
    },
    setItem(key, value) {
      storage.set(key, String(value))
    },
    removeItem(key) {
      storage.delete(key)
    }
  }
}

const expiresAt = '2099-01-01T00:00:00.000Z'
persistAuthCredentials('opaque-token', expiresAt)
assert.equal(readAuthAccessToken(), 'opaque-token')
assert.equal(readAuthExpiresAt(), Date.parse(expiresAt))
assert.equal(hasValidAuthSession(Date.parse('2098-01-01T00:00:00.000Z')), true)
assert.deepEqual(buildBearerHeaders(), { Authorization: 'Bearer opaque-token' })

storage.set(AUTH_EXPIRES_AT_KEY, '2020-01-01T00:00:00.000Z')
assert.equal(hasValidAuthSession(Date.parse('2021-01-01T00:00:00.000Z')), false)

storage.set(AUTH_ACCESS_TOKEN_KEY, '')
assert.deepEqual(buildBearerHeaders(), {})

assert.throws(
  () => persistAuthCredentials('', expiresAt),
  /未返回有效的认证凭证/
)

clearAuthCredentials()
assert.equal(storage.has(AUTH_ACCESS_TOKEN_KEY), false)
assert.equal(storage.has(AUTH_EXPIRES_AT_KEY), false)

console.log('auth session storage tests passed')
