class Support::Token < ApplicationRecord
  attr_accessor :auth_headers, :batch_request

  belongs_to :user

  validates :current, :client, :expiry, presence: true
  validates :client, uniqueness: { case_sensitive: true }

  scope :updated_at_less_than, ->(date) { where('updated_at < ?', date) }

  def not_batch
    throw(:abort) if reuse_token?
  end

  def create_token
    token = TokenFactory.new.create

    self.client = token.client
    self.current = token.token_hash
    self.expiry = token.expiry

    build_auth_headers(token.token)

    token
  end

  def refresh
    token = TokenFactory.new.create

    self.previous = current
    self.current = token.token_hash
    self.expiry = token.expiry

    build_auth_headers(token.token)

    token
  end

  def validate_token(token)
    return true if token_is_valid?(current, token)

    self.batch_request = token_is_valid?(previous, token)
  end

  def is_batch?
    batch_request || false
  end

  def reuse_token?
    Time.current - updated_at < 5.seconds
  end

  private
    def build_auth_headers(token)
      self.auth_headers = {
        'access-token' => token,
        'client' => client,
        'uid' => user_id.to_s,
        'expiry' => Time.now.to_i.to_s
      }
    end

    def token_is_valid?(token_hash, token)
      TokenFactory.new.validate_token(token_hash, token)
    end
end
