class Asset < ApplicationRecord

  STICKER = 'Sticker'

  has_one_attached :file

  include PgSearch::Model
  pg_search_scope :pg_search,
                  against: [:title, :tags],
                  associated_against: {
                    file_blob: [:filename, :content_type]
                  },
                  using: {
                    tsearch: { prefix: true }
                  }

  before_validation :remove_empty_tags

  scope :stickets, ->() { where("tags @> ?", "{#{STICKER}}") }

  scope :by_last_modified, ->(rev) { order(updated_at: rev ? :asc : :desc, id: rev ? :desc : :asc) }
  scope :by_filename, ->(rev) { order(title: rev ? :desc : :asc) }
  scope :simple_search, ->(q) { pg_search(q) unless q.blank? }


private

  def remove_empty_tags
    %w"tags".map do |k|
      self.send "#{k}=", self.send(k).reject { |v| v.blank? } unless self.send(k).blank?
    end
  end

end
