export const AUTH_ACCESS_TOKEN_KEY = 'x-financial-auth-access-token'
export const AUTH_EXPIRES_AT_KEY = 'x-financial-auth-expires-at'
export const AUTH_SESSION_EXPIRED_EVENT = 'x-financial:auth-expired'

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

export function readAuthAccessToken() {
  if (!canUseSessionStorage()) {
    return ''
  }
  return String(window.sessionStorage.getItem(AUTH_ACCESS_TOKEN_KEY) || '').trim()
}

export function readAuthExpiresAt() {
  if (!canUseSessionStorage()) {
    return 0
  }
  const raw = String(window.sessionStorage.getItem(AUTH_EXPIRES_AT_KEY) || '').trim()
  if (!raw) {
    return 0
  }
  const timestamp = Date.parse(raw)
  return Number.isFinite(timestamp) ? timestamp : 0
}

export function hasValidAuthSession(now = Date.now()) {
  const accessToken = readAuthAccessToken()
  const expiresAt = readAuthExpiresAt()
  return Boolean(accessToken && expiresAt && expiresAt > now)
}

export function persistAuthCredentials(accessToken, expiresAt) {
  if (!canUseSessionStorage()) {
    return
  }
  const normalizedToken = String(accessToken || '').trim()
  const normalizedExpiresAt = String(expiresAt || '').trim()
  if (!normalizedToken || !normalizedExpiresAt || !Number.isFinite(Date.parse(normalizedExpiresAt))) {
    throw new Error('登录接口未返回有效的认证凭证。')
  }
  window.sessionStorage.setItem(AUTH_ACCESS_TOKEN_KEY, normalizedToken)
  window.sessionStorage.setItem(AUTH_EXPIRES_AT_KEY, normalizedExpiresAt)
}

export function clearAuthCredentials() {
  if (!canUseSessionStorage()) {
    return
  }
  window.sessionStorage.removeItem(AUTH_ACCESS_TOKEN_KEY)
  window.sessionStorage.removeItem(AUTH_EXPIRES_AT_KEY)
}

export function buildBearerHeaders() {
  const accessToken = readAuthAccessToken()
  if (!accessToken) {
    return {}
  }
  return { Authorization: `Bearer ${accessToken}` }
}

export function notifyAuthSessionExpired() {
  if (typeof window === 'undefined' || typeof window.dispatchEvent !== 'function') {
    return
  }
  const event = typeof CustomEvent === 'function'
    ? new CustomEvent(AUTH_SESSION_EXPIRED_EVENT)
    : { type: AUTH_SESSION_EXPIRED_EVENT }
  window.dispatchEvent(event)
}
