require 'bcrypt'

class TokenFactory
  LIFESPAN = 2.weeks

  def self.remove_expired_tokens
    ::Token.updated_at_less_than(LIFESPAN.ago).map(&:destroy!)
  end

  def create
    Token.new(client, token, token_hash, expiry)
  end

  def secure_string
    SecureRandom.urlsafe_base64
  end

  def client
    secure_string
  end

  def token
    @token ||= secure_string
  end

  def token_hash(cost=10)
    BCrypt::Password.create(token, cost: cost)
  end

  def expiry
    (Time.zone.now + LIFESPAN).to_i
  end

  def validate_token(token_hash, token)
    BCrypt::Password.new(token_hash).is_password?(token)
  rescue
  end

  Token = Struct.new(:client, :token, :token_hash, :expiry)
end
