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

require 'contrast/components/logger'
require 'contrast/agent/reporting/reporting_events/reporting_event'
require 'contrast/agent/reporting/reporting_events/discovered_route'

module Contrast
  module Agent
    module Reporting
      # This is the new ApplicationInventory class which will include all the needed information
      # for the new reporting system to report. Reporting those components or details discovered at
      # startup, or as soon as possible, but not necessarily seen used by the application. Each of
      # these messages should only be sent once per application.
      class ApplicationInventory < Contrast::Agent::Reporting::ApplicationReportingEvent
        # @param [Array<Contrast::Agent::Reporting::DiscoveredRoute>] the routes registered to this application, as
        #   discovered during first request processing.
        attr_reader :routes

        class << self
          def convert app_update_dtm
            app_inventory = new
            app_inventory.attach_data app_update_dtm
            app_inventory
          end
        end

        def file_name
          'applications-inventory'
        end

        def initialize
          @routes = []
          @event_type = :application_inventory
          @event_method = :POST
          @event_endpoint = Contrast::Agent::Reporting::Endpoints.application_inventory
          super
        end

        def to_controlled_hash
          {
              session_id: @agent_session_id_value,
              routes: routes.map(&:to_controlled_hash)
          }
        end

        # @param inventory_dtm [Contrast::Api::Dtm::ApplicationUpdate]
        # @return [Contrast::Agent::Reporting::ApplicationInventory]
        def attach_data inventory_dtm
          inventory_dtm.routes.each do |route|
            @routes << Contrast::Agent::Reporting::DiscoveredRoute.convert(route)
          end
        end
      end
    end
  end
end