class Tag < ApplicationRecord
  include TokenizedLike

  has_and_belongs_to_many :recipes

  scope :by_name, ->(names) { where(lowercase_name: Array.wrap(names).map { |n| n.downcase }) }

  validates :name, presence: true, length: {maximum: 250}, uniqueness: { case_sensitive: false }

  before_save :set_lowercase_name

  def is?(tag_name)
    tag_name.casecmp(self.name) == 0
  end

  def self.search(query)
    token = query.to_s.strip

    if token.empty?
      Tag.none
    else
      Tag.matches_token(:name, token)
    end
  end

  private

  def set_lowercase_name
    self.lowercase_name = self.name.downcase
  end

end
