# frozen_string_literal: true

module Gitlab
  module BackgroundMigration
    class UpdateOwaspTop10DefaultOfVulnerabilityReads < BatchedMigrationJob
      scope_to ->(relation) { relation.where(owasp_top_10: nil) }
      feature_category :vulnerability_management
      operation_name :set_owasp_top_10_null_to_int

      UPDATE_SQL = <<-SQL.squish
        UPDATE vulnerability_reads AS vr
        SET owasp_top_10 = -1
        FROM (?) AS selected_ids
        WHERE vr.id = selected_ids.id
      SQL

      class VulnerabilitiesRead < ::ApplicationRecord
        self.table_name = 'vulnerability_reads'
      end

      def perform
        each_sub_batch do |sub_batch|
          cte = Gitlab::SQL::CTE.new(:batched_relation,
            sub_batch.limit(50)
          )

          filtered_results = cte
            .apply_to(VulnerabilitiesRead.all)
            .select('vulnerability_reads.id AS id')

          update_query = VulnerabilitiesRead.sanitize_sql([UPDATE_SQL, filtered_results])

          connection.execute(update_query)
        end
      end
    end
  end
end
