# frozen_string_literal: true

module EE
  module Banzai
    module Filter
      module References
        # HTML filter that replaces vulnerability references with links. References to
        # vulnerabilities that do not exist are ignored.
        #
        # This filter supports cross-project/group references.
        module VulnerabilityReferenceFilter
          extend ActiveSupport::Concern

          def references_in(text, pattern = object_class.reference_pattern)
            text.gsub(pattern) do |match|
              symbol = $~[object_sym]
              if object_class.reference_valid?(symbol)
                yield match, symbol.to_i, $~[:project], $~[:namespace], $~
              else
                match
              end
            end
          end

          def unescape_link(href)
            return href if href =~ object_class.reference_pattern

            super
          end

          def url_for_object(vulnerability, project)
            urls = ::Gitlab::Routing.url_helpers
            urls.project_security_vulnerability_url(project, vulnerability, only_path: context[:only_path])
          end

          def data_attributes_for(text, project, object, link_content: false, link_reference: false)
            {
              original:       escape_html_entities(text),
              link:           link_content,
              link_reference: link_reference,
              project:        project.id,
              object_sym =>   object.id
            }
          end

          def parent_records(parent, ids)
            return ::Vulnerability.none if ids.blank? || parent.nil?

            parent.vulnerabilities.id_in(ids.to_a)
          end

          def record_identifier(record)
            record.id.to_i
          end

          def parent_type
            :project
          end
        end
      end
    end
  end
end
