# frozen_string_literal: true

class ModifyKubernetesResourceLocationIndexToVulnerabilityOccurrences < Gitlab::Database::Migration[1.0]
  disable_ddl_transaction!

  OLD_CLUSTER_ID_INDEX_NAME = 'index_vulnerability_occurrences_on_location_cluster_id'
  OLD_AGENT_ID_INDEX_NAME = 'index_vulnerability_occurrences_on_location_agent_id'

  NEW_CLUSTER_ID_INDEX_NAME = 'index_vulnerability_occurrences_on_location_k8s_cluster_id'
  NEW_AGENT_ID_INDEX_NAME = 'index_vulnerability_occurrences_on_location_k8s_agent_id'

  def up
    add_concurrent_index :vulnerability_occurrences, "(location -> 'kubernetes_resource' -> 'cluster_id')",
                         using: 'GIN',
                         where: 'report_type = 7',
                         name: NEW_CLUSTER_ID_INDEX_NAME

    add_concurrent_index :vulnerability_occurrences, "(location -> 'kubernetes_resource' -> 'agent_id')",
                         using: 'GIN',
                         where: 'report_type = 7',
                         name: NEW_AGENT_ID_INDEX_NAME

    remove_concurrent_index_by_name :vulnerability_occurrences, OLD_CLUSTER_ID_INDEX_NAME
    remove_concurrent_index_by_name :vulnerability_occurrences, OLD_AGENT_ID_INDEX_NAME
  end

  def down
    add_concurrent_index :vulnerability_occurrences, "(location -> 'cluster_id')",
                         using: 'GIN',
                         where: 'report_type = 7',
                         name: OLD_CLUSTER_ID_INDEX_NAME

    add_concurrent_index :vulnerability_occurrences, "(location -> 'agent_id')",
                         using: 'GIN',
                         where: 'report_type = 7',
                         name: OLD_AGENT_ID_INDEX_NAME

    remove_concurrent_index_by_name :vulnerability_occurrences, NEW_CLUSTER_ID_INDEX_NAME
    remove_concurrent_index_by_name :vulnerability_occurrences, NEW_AGENT_ID_INDEX_NAME
  end
end
