module JamRuby
  class ReviewSummary < ActiveRecord::Base
    attr_accessible :target, :target_id, :target_type, :avg_rating, :wilson_score, :review_count
    belongs_to :target, polymorphic: true

    validates :avg_rating, presence:true, numericality: true
    validates :review_count, presence:true, numericality: {only_integer: true}
    validates :wilson_score, presence:true, numericality: {greater_than_or_equal_to:0, less_than_or_equal_to:1}
    validates :target_id, presence:true, uniqueness:true

    class << self

      # Query review_summaries using target type, id, and minimum review count
      # * target_type: Only return review summaries for given target type
      # * target_id: Only return review summary for given target type
      # * minimum_reviews: Only return review summary made up of at least this many reviews
      # * arel: start with pre-queried reviews (arel object)
      # sorts by wilson score
      def index(options={})
        options ||= {}
        if (options.key?(:arel))
          arel = options[:arel].order("wilson_score DESC")
        else
          arel = ReviewSummary.order("wilson_score DESC")
        end

        if (options.key?(:target_type))
          arel = arel.where("target_type=?", options[:target_type])
        end

        if (options.key?(:target_id))
          arel = arel.where("target_id=?", options[:target_id])
        end

        if (options.key?(:minimum_reviews))
          arel = arel.where("review_count>=?", options[:minimum_reviews])
        end

        arel
      end
    end
  end
end