module JamRuby
  class FanInvitation < ActiveRecord::Base

    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"

    self.primary_key = 'id'
    belongs_to :sender, :inverse_of => :sent_fan_invitations, :class_name => "JamRuby::User", :foreign_key => "sender_id"
    belongs_to :receiver, :inverse_of => :received_fan_invitations, :class_name => "JamRuby::User", :foreign_key => "receiver_id"
    belongs_to :music_session, :inverse_of => :fan_invitations, :class_name => "JamRuby::MusicSession", :foreign_key => "music_session_id"

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

    validate :require_sender_in_music_session, :require_are_friends

    private

    def require_sender_in_music_session
      unless music_session.part_of_session? sender
         errors.add(:music_session, MEMBERSHIP_REQUIRED_OF_MUSIC_SESSION)
      end
    end

    def require_are_friends
      unless receiver.friends.exists? sender
        errors.add(:receiver, FRIENDSHIP_REQUIRED_VALIDATION_ERROR)
      end
    end
  end
end
