# == Schema Information
#
# Table name: views
#
#  id            :integer          not null, primary key
#  viewable_id   :integer
#  viewable_type :string
#  user_id       :integer
#  created_at    :datetime         not null
#  updated_at    :datetime         not null
#

class View < ApplicationRecord
  # *current_user* views *viewable*
  include Trackable

  belongs_to :viewable, polymorphic: true, counter_cache: true
  belongs_to :user

  validates_presence_of :user, :viewable

  before_create :current_time_greater_than_last

  scope :created_last, ->(user) { where(user: user).order('created_at DESC').limit(1) }

  def recipient
    viewable
  end

  private

  def current_time_greater_than_last
    last_view = viewable.views.created_last(user).first

    unless last_view.blank?
      return false if Time.now < (last_view.created_at + 1.days)
    end

    true
  end

end