75000
  8   åˆl–Ãa¾”*i?u8 …p/Üiå1hß�þY|¤YÇ )deç_$þö„O	ïõøÅô 9ì    å# Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

class SearchKnowledgeBaseBackend
  attr_reader :knowledge_base, :user

  # @param [Hash] params the paramsused to initialize search instance
  # @option params [KnowledgeBase, <KnowledgeBase>] :knowledge_base (nil) knowledge base instance
  # @option params [KnowledgeBase::Locale, <KnowledgeBase::Locale>, String] :locale (nil) KB Locale or string identifier
  # @option params [KnowledgeBase::Category] :scope (nil) optional search scope
  # @option params [Symbol]  :flavor (:public) agent or public to indicate source and narrow down to internal or public answers accordingly
  # @option params [String, Array<String>] :index (nil) indexes to limit search to, searches all indexes if nil
  # @option params [Integer] :limit per page param for paginatin
  # @option params [Boolean] :highlight_enabled (true) highlight matching text
  # @option params [Hash] :highlight_options (nil) Elasticsearch highlight settings (pre_tags, post_tags,
  #   fragment_size, number_of_fragments, no_match_size, ...) applied to every highlighted field.
  #   Without it Elasticsearch's defaults apply, i.e. up to five 100 character <em> marked fragments.
  # @option params [Hash<String=>String>, Hash<Symbol=>Symbol>] :order_by hash with column => asc/desc
  # @option params [User] :user (nil) the searching user, whose access the results are filtered by

  def initialize(params)
    @params = params.except(:user).compact
    @user   = params[:user]

    prepare_scope_ids
  end

  def search(query, pagination: nil)
    raw_results = raw_results(query, pagination: pagination)

    filtered = filter_results raw_results

    if pagination
      filtered = filtered.slice pagination.offset, pagination.limit
    elsif @params[:limit]
      filtered = filtered.slice 0, @params[:limit]
    end

    filtered
  end

  def search_fallback(query, indexes)
    indexes.flat_map { |index| search_fallback_for_index(query, index) }
  end

  def search_fallback_for_index(query, index)
    index
      .constantize
      .search_sql_text_fallback("%#{query}%")
      .apply_kb_scope(@cached_scope_ids)
      .where(kb_locale: kb_locales)
      .reorder(**search_fallback_order)
      .pluck(:id)
      .map { |id| { id: id, type: index } }
  end

  def search_fallback_order
    @params[:order_by].presence || { updated_at: :desc }
  end

  def raw_results(query, pagination: nil)
    return search_fallback(query, indexes) if !SearchIndexBackend.enabled?

    results = SearchIndexBackend
      .search(query, indexes, options(query, pagination: pagination))
      .map do |hash|
        hash[:id]        = hash[:id].to_i
        hash[:highlight] = repair_highlighted_entities(hash[:highlight]) if hash[:highlight]
        hash
      end

    sort_by_relevance results
  end

  # The texts are indexed HTML-escaped (see the translations' #search_index_attribute_lookup), so
  #   `&amp;` carries an `amp` term of its own. A query that matches every term â€” `*` â€” marks that
  #   one too and tears the entity apart, as `&<em>amp</em>;`, which no consumer decodes back to
  #   `&`. Those terms exist only because of the escaping, so drop the tags inside an entity.
  def repair_highlighted_entities(highlight)
    tags   = Regexp.union(highlight_tags)
    entity = %r{&(?:#{tags})*\w+(?:#{tags})*;}

    highlight.transform_values do |fragments|
      fragments.map { |fragment| fragment.gsub(entity) { |match| match.gsub(tags, '') } }
    end
  end

  # Elasticsearch applies its `<em>` defaults per tag, so a caller naming only one of them still
  #   gets the other one's default.
  def highlight_tags
    highlight_options = @params[:highlight_options].to_h

    (highlight_options[:pre_tags].presence || ['<em>']) + (highlight_options[:post_tags].presence || ['</em>'])
  end

  # Elasticsearch is asked once per index and the responses are concatenated
  #   (SearchIndexBackend.search), so the combined list arrives grouped by index instead of b