module JamRuby
  class JamblasterPairingRequest < ActiveRecord::Base

    belongs_to :user, class_name: 'JamRuby::User'
    belongs_to :jamblaster, class_name: 'JamRuby::Jamblaster', foreign_key: :jamblaster_id

    validates :user, presence: true
    validates :jamblaster, presence: true
    validates :jamblaster_client_id, presence: true
    validates :vtoken, presence: true

    def key
      sibling_key
    end

    def activate(key)
      JamblasterPairingRequest.transaction do
        JamblasterPairingRequest.where(jamblaster_id: jamblaster_id).update_all(active: false)
        self.active = true
        self.sibling_key = key
        if !self.save
          raise ActiveRecord::Rollback
        end
      end
    end

  end
end
