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

  belongs_to :user
  belongs_to :support_user, optional: true, class_name: 'Support::User'

  before_save :not_batch, unless: :new_record?

  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 create_support_token(support_user_id)
    self.support_user_id = support_user_id
    token = create_token

    self.jwt = JWT.encode(auth_headers, nil, 'none')
    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,
        'support-uid' => support_user_id.to_s
      }
    end

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