# frozen_string_literal: true

module Gitlab
  module BackgroundMigration
    # Backfills has_remediations column for vulnerability_reads table.
    class BackfillHasRemediationsOfVulnerabilityReads < BatchedMigrationJob
      operation_name :set_has_remediations
      feature_category :database

      UPDATE_SQL = <<~SQL
        UPDATE
          vulnerability_reads
        SET
          has_remediations = true
        FROM
          (%<subquery>s) as sub_query
        WHERE
          vulnerability_reads.vulnerability_id = sub_query.vulnerability_id
      SQL

      def perform
        each_sub_batch do |sub_batch|
          reset_has_remediations_attribute(sub_batch)

          update_query = update_query_for(sub_batch)

          connection.execute(update_query)
        end
      end

      private

      def reset_has_remediations_attribute(sub_batch)
        sub_batch.update_all(has_remediations: false)
      end

      def update_query_for(sub_batch)
        subquery = sub_batch.joins("
          INNER JOIN vulnerability_occurrences ON
          vulnerability_reads.vulnerability_id = vulnerability_occurrences.vulnerability_id")
          .select("vulnerability_reads.vulnerability_id, vulnerability_occurrences.id")
          .joins("INNER JOIN vulnerability_findings_remediations ON
          vulnerability_occurrences.id = vulnerability_findings_remediations.vulnerability_occurrence_id")

        format(UPDATE_SQL, subquery: subquery.to_sql)
      end
    end
  end
end
