# frozen_string_literal: true

module EE
  module Gitlab
    module BackgroundMigration
      module RemoveDuplicatedCsFindingsWithoutVulnerabilityId
        extend ::Gitlab::Utils::Override

        class Finding < ActiveRecord::Base
          include ::ShaAttribute
          include ::EachBatch

          BROKEN_FINGERPRINT_LENGTH = 40

          scope :with_broken_fingerprint, -> { where("length(location_fingerprint) = ?", BROKEN_FINGERPRINT_LENGTH) }

          self.table_name = 'vulnerability_occurrences'

          REPORT_TYPES = {
            container_scanning: 2
          }.with_indifferent_access.freeze

          enum report_type: REPORT_TYPES

          sha_attribute :location_fingerprint
        end

        override :perform
        def perform(start_id, stop_id)
          Finding.select(:id, :project_id, :primary_identifier_id, :location_fingerprint, :scanner_id)
          .container_scanning
          .where(id: start_id..stop_id, vulnerability_id: nil)
          .with_broken_fingerprint
          .each do |finding|
            fixed_fingerprint = ::Gitlab::Database::ShaAttribute.new.serialize(finding.location_fingerprint).to_s
            duplicate = Finding.container_scanning
                               .where(project_id: finding.project_id,
                                      primary_identifier_id: finding.primary_identifier_id,
                                      scanner_id: finding.scanner_id,
                                      location_fingerprint: fixed_fingerprint,
                                      vulnerability_id: nil)
                               .where.not(id: finding.id).first

            next if duplicate.blank?

            Finding.transaction do
              duplicate.delete

              finding.update(location_fingerprint: fixed_fingerprint)
            end
          end
        end
      end
    end
  end
end
