import { randomBytes } from 'crypto'

let activeToken: string | null = null

export function generateToken(): string {
  activeToken = randomBytes(32).toString('base64url')
  return activeToken
}

export function validateToken(token: string | undefined): boolean {
  if (!activeToken) return false
  if (!token) return false
  // Constant-time comparison
  if (token.length !== activeToken.length) return false
  let result = 0
  for (let i = 0; i < token.length; i++) {
    result |= token.charCodeAt(i) ^ activeToken.charCodeAt(i)
  }
  return result === 0
}

export function getActiveToken(): string | null {
  return activeToken
}
