# frozen_string_literal: true

module Gitlab
  module BackgroundMigration
    # Backfills the `vulnerability_reads.casted_cluster_agent_id` column
    class BackfillVulnerabilityReadsClusterAgent < Gitlab::BackgroundMigration::BatchedMigrationJob
      operation_name :update_all
      feature_category :database

      CLUSTER_AGENTS_JOIN = <<~SQL
        INNER JOIN cluster_agents
        ON CAST(vulnerability_reads.cluster_agent_id AS bigint) = cluster_agents.id AND
        vulnerability_reads.project_id = cluster_agents.project_id
      SQL

      CLUSTER_IMAGE_SCANNING_REPORT_TYPE = 7

      scope_to ->(relation) { relation.where(report_type: CLUSTER_IMAGE_SCANNING_REPORT_TYPE) }

      def perform
        # This allow_cross_joins_across_databases call will never be removed.
        # The definition of this migration cannot function after the decomposition
        # of the Sec database. As such, it must be finalised before the decomposition.
        Gitlab::Database.allow_cross_joins_across_databases(
          url: 'https://gitlab.com/gitlab-org/gitlab/-/merge_requests/164505'
        ) do
          each_sub_batch do |sub_batch|
            sub_batch
              .joins(CLUSTER_AGENTS_JOIN)
              .update_all('casted_cluster_agent_id = CAST(vulnerability_reads.cluster_agent_id AS bigint)')
          end
        end
      end
    end
  end
end
