# frozen_string_literal: true

class SwapVulnerabilityFeedbackPipelineIdConvertToBigint < Gitlab::Database::Migration[2.2]
  include Gitlab::Database::MigrationHelpers::Swapping

  milestone '17.0'
  disable_ddl_transaction!

  TABLE_NAME = 'vulnerability_feedback'
  COLUMN_NAME = "pipeline_id"
  COLUMN_TO_BIGINT_NAME = "pipeline_id_convert_to_bigint"
  INDEX_TO_BIGINT_NAME = "index_vulnerability_feedback_on_pipeline_id_bigint"
  INDEX_NAME = "index_vulnerability_feedback_on_pipeline_id"

  def up
    swap
  end

  def down
    add_concurrent_index TABLE_NAME, COLUMN_TO_BIGINT_NAME, name: INDEX_TO_BIGINT_NAME

    swap

    # Revert to original state before the migration
    add_concurrent_index TABLE_NAME, COLUMN_TO_BIGINT_NAME, name: INDEX_TO_BIGINT_NAME
  end

  def swap
    with_lock_retries(raise_on_exhaustion: true) do
      # Not locking ci_pipelines as it's an LFK column
      lock_tables(TABLE_NAME)

      swap_columns(TABLE_NAME, COLUMN_NAME, COLUMN_TO_BIGINT_NAME)

      reset_trigger_function(:trigger_2428b5519042)

      # No defaults to swap as the column is not a PK one

      execute "DROP INDEX #{INDEX_NAME}"
      rename_index TABLE_NAME, INDEX_TO_BIGINT_NAME, INDEX_NAME
    end
  end
end
