module JamRuby
  class Invitation < ActiveRecord::Base

    INVITATION_NOT_TEACHER_VALIDATION_ERROR = "Lessons can only sent invitations to teachers"
    FRIENDSHIP_REQUIRED_VALIDATION_ERROR = "You can only invite friends"
    MEMBERSHIP_REQUIRED_OF_MUSIC_SESSION = "You must be a member of the music session to send invitations on behalf of it"
    JOIN_REQUEST_IS_NOT_FOR_RECEIVER_AND_MUSIC_SESSION = "You can only associate a join request with an invitation if that join request comes from the invited user and if it's for the same music session"

    self.primary_key = 'id'
    belongs_to :sender, :inverse_of => :sent_invitations, :class_name => "JamRuby::User", :foreign_key => "sender_id"
    belongs_to :receiver, :inverse_of => :received_invitations, :class_name => "JamRuby::User", :foreign_key => "receiver_id"
    belongs_to :music_session, :inverse_of => :invitations, :class_name => "JamRuby::MusicSession", :foreign_key => "music_session_id"
    belongs_to :join_request, :inverse_of => :invitations, :class_name => "JamRuby::JoinRequest"

    validates :sender, :presence => true
    validates :receiver, :presence => true
    validates :music_session, :presence => true

    validate :require_sender_in_music_session, :require_are_friends_or_requested_to_join_or_teacher

    private

    def require_sender_in_music_session
      if music_session && !music_session.part_of_session?(sender)
        errors.add(:music_session, MEMBERSHIP_REQUIRED_OF_MUSIC_SESSION)
      end
    end

    def require_are_friends_or_requested_to_join_or_teacher
      if !join_request.nil? && (join_request.user != receiver || join_request.music_session != music_session)
        errors.add(:join_request, JOIN_REQUEST_IS_NOT_FOR_RECEIVER_AND_MUSIC_SESSION)
      elsif music_session.is_lesson?
        if (receiver != music_session.lesson_session.teacher)
          errors.add(:receiver, INVITATION_NOT_TEACHER_VALIDATION_ERROR)
        end
      elsif join_request.nil?
        # we only check for friendship requirement if this was not in response to a join_request and not a lesson
        if !receiver.friends.exists?(sender.id)
          errors.add(:receiver, FRIENDSHIP_REQUIRED_VALIDATION_ERROR)
        end
      end
    end
  end
end
