# frozen_string_literal: true

class SchedulePopulateVulnerabilityHistoricalStatistics < ActiveRecord::Migration[6.0]
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false
  DELAY_INTERVAL = 2.minutes.to_i
  BATCH_SIZE = 50
  MIGRATION = 'PopulateVulnerabilityHistoricalStatistics'

  disable_ddl_transaction!

  class Vulnerability < ActiveRecord::Base
    self.table_name = 'vulnerabilities'

    include ::EachBatch
  end

  def up
    return unless Gitlab.ee?

    Vulnerability.select('project_id').distinct.each_batch(of: BATCH_SIZE, column: 'project_id') do |project_batch, index|
      migrate_in(index * DELAY_INTERVAL, MIGRATION, [project_batch.pluck(:project_id)])
    end
  end

  def down
    # no-op
  end
end
