# frozen_string_literal: true

module Integrations
  module ChatMessage
    class VulnerabilityMessage < ::Integrations::ChatMessage::BaseMessage
      attr_reader :title
      attr_reader :identifiers
      attr_reader :severity
      attr_reader :vulnerability_url

      def initialize(params)
        @project_name = params[:project_name] || params.dig(:project, :path_with_namespace)
        @project_url = params.dig(:project, :web_url) || params[:project_url]
        @title = params.dig(:object_attributes, :title)
        @identifiers = params.dig(:object_attributes, :identifiers)
        @severity = params.dig(:object_attributes, :severity)
        @vulnerability_url = params.dig(:object_attributes, :url)
      end

      def attachments
        [{
          title: title,
          title_link: vulnerability_url,
          color: attachment_color,
          fields: attachment_fields
        }]
      end

      def message
        "Vulnerability detected in #{project_link}"
      end

      private

      def attachment_color
        "#C95823"
      end

      def attachment_fields
        [
          {
            title: "Severity",
            value: severity.to_s.humanize,
            short: true
          },
          {
            title: "Identifiers",
            value: ::Slack::Messenger::Util::LinkFormatter.format(identifiers_links),
            short: true
          }
        ]
      end

      def identifiers_links
        @identifiers.map { |i| identifier_link(i) }.join(I18n.t(:'support.array.words_connector'))
      end

      def identifier_link(identifier)
        link(identifier[:name], identifier[:url])
      end

      def project_link
        link(project_name, project_url)
      end
    end
  end
end
