# Copyright (c) 2022 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
# frozen_string_literal: true

require 'base64'
require 'contrast/agent/assess/contrast_event'
require 'contrast/agent/assess/events/source_event'

module Contrast
  module Agent
    module Reporting
      # This is the new FindingEventSource class which will include all the needed information for the new reporting
      # system to relay this information in the Finding/Trace messages. These FindingEventSource are used by TeamServer
      # to construct the vulnerability information for the assess feature. They indicate the type of data that the
      # event represents.
      class FindingEventSource
        # @return [String] the name of the source
        attr_reader :name
        # @return [String] the type of the source
        attr_reader :type

        class << self
          # @param event [Contrast::Agent::Assess::Events::ContrastEvent] the event to pull the source off of
          # @return [Contrast::Agent::Reporting::FindingEventSource]
          def convert event
            return unless event.cs__is_a?(Contrast::Agent::Assess::Events::SourceEvent)

            report = new
            report.attach_data(event)
            report
          end
        end

        # Parse the data from a Contrast::Agent::Assess::Events::SourceEvent to attach what is required for reporting
        # to TeamServer to this Contrast::Agent::Reporting::FindingEventSource
        #
        # @param event [Contrast::Agent::Assess::Events::SourceEvent] the event to pull the source off of
        def attach_data event
          @name = event.source_name
          @type = event.source_type
        end

        # Convert the instance variables on the class, and other information, into the identifiers required for
        # TeamServer to process the JSON form of this message.
        #
        # @return [Hash]
        # @raise [ArgumentError]
        def to_controlled_hash
          validate
          {
              sourceName: name, # rubocop:disable Security/Module/Name
              sourceType: type
          }
        end

        def validate
          raise(ArgumentError, "#{ self } did not have a proper type. Unable to continue.") unless type && !type.empty?
        end
      end
    end
  end
end