class Response < ApplicationRecord
  validates :respondent_id, :answer_choice_id, presence: true
  validate :not_duplicate_response
  validate :does_not_respond_to_own_poll

  belongs_to :answer_choice,
    class_name: 'AnswerChoice',
    foreign_key: :answer_choice_id,
    primary_key: :id
  
  belongs_to :respondent,
    class_name: 'User',
    foreign_key: :respondent_id,
    primary_key: :id
  
  has_one :question,
    through: :answer_choice,
    source: :question
  
  def sibling_responses
    question.responses.where.not(id: self.id)
  end

  def respondent_already_answered?
    sibling_responses.exists?(respondent_id: self.respondent_id)
  end

  def not_duplicate_response
    if respondent_already_answered?
      errors[:respondent_id] << 'can\'t respond to the same question more than once'
    end
  end

  def does_not_respond_to_own_poll
    if answer_choice.question.poll.author_id == self.respondent_id
      errors[:respondent_id] << 'can\'t respond to your own poll'
    end
  end
end