class Recipe < ApplicationRecord
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks

  belongs_to :user
  belongs_to :category
  belongs_to :cuisine

  has_many :ratings, dependent: :destroy
  has_many :comments, dependent: :destroy
  has_many :favourites, dependent: :destroy
  has_many :favourited_by, through: :favourites, source: :user
  has_many :contents, dependent: :destroy
  has_many :ingredients, through: :contents

  has_and_belongs_to_many :tags

  accepts_nested_attributes_for :contents, allow_destroy: true, reject_if: proc { |att| att['quantity'].blank? }

  validates_associated :contents
  validates_presence_of :name, :description
  validates_uniqueness_of :name

  PREFERENCES = [:vegeterian, :spicy, :low_calorie]

  mount_uploaders :images, RecipeImageUploader

  def calories
    CalculateCalories.call(self)
  end

  def average_rating
    CalculateRating.call(self)
  end

  def is_low_calorie?
    self.calories < 300
  end
end
