# frozen_string_literal: true

module Security
  module Ingestion
    module Tasks
      # Ingests the data for the `Vulnerabilities`::Flag` model.
      class IngestVulnerabilityFlags < AbstractTask
        include BulkInsertableTask

        self.model = Vulnerabilities::Flag
        self.unique_by = :index_vulnerability_flags_on_unique_columns
        self.uses = :id

        private

        def attributes
          finding_maps.flat_map { |finding_map| flag_attributes_for(finding_map) }
        end

        def after_ingest
          model.where(finding: finding_ids).where.not(id: return_data).delete_all # rubocop:disable CodeReuse/ActiveRecord
        end

        def finding_ids
          finding_maps.map(&:finding_id)
        end

        def flag_attributes_for(finding_map)
          finding_map.report_finding.flags.map do |vulnerability_flag|
            vulnerability_flag.to_h.merge!(vulnerability_occurrence_id: finding_map.finding_id)
          end
        end
      end
    end
  end
end
