# frozen_string_literal: true

class PartitionVulnerabilityArchivedRecords < Gitlab::Database::Migration[2.2]
  VULNERABILITY_ID_INDEX_NAME = 'index_vulnerability_archived_records_on_vulnerability_id'
  NEW_VULNERABILITY_ID_INDEX_NAME = 'index_vulnerability_archived_records_on_unique_attributes'
  ARCHIVE_ID_INDEX_NAME = 'index_vulnerability_archived_records_on_archive_id_and_id'
  PARTITIONED_TABLE_OPTIONS = {
    primary_key: %i[id date],
    options: 'PARTITION BY RANGE (date)'
  }.freeze

  milestone '17.11'

  def up
    drop_table :vulnerability_archived_records # rubocop:disable Migration/DropTable -- We are temporarily dropping the table

    create_table :vulnerability_archived_records, **PARTITIONED_TABLE_OPTIONS do |t| # rubocop:disable Migration/EnsureFactoryForTable -- false positive
      t.timestamps_with_timezone null: false

      t.bigserial :id, null: false
      t.date :date, null: false
      t.bigint :project_id, null: false, index: true
      t.references :archive,
        null: false, foreign_key: { on_delete: :cascade, to_table: 'vulnerability_archives' }, index: false

      t.bigint :vulnerability_identifier, null: false
      t.jsonb :data, null: false, default: {}

      t.index %i[vulnerability_identifier date], name: NEW_VULNERABILITY_ID_INDEX_NAME, unique: true
      t.index %i[archive_id id], name: ARCHIVE_ID_INDEX_NAME
    end
  end

  def down
    drop_table :vulnerability_archived_records

    create_table :vulnerability_archived_records do |t| # rubocop:disable Migration/EnsureFactoryForTable -- false positive
      t.timestamps_with_timezone null: false

      t.bigint :project_id, null: false, index: true
      t.references :archive,
        null: false, foreign_key: { on_delete: :cascade, to_table: 'vulnerability_archives' }, index: false

      t.bigint :vulnerability_identifier, null: false, index: { name: VULNERABILITY_ID_INDEX_NAME, unique: true }
      t.jsonb :data, null: false, default: {}

      t.index %i[archive_id id], name: ARCHIVE_ID_INDEX_NAME
    end
  end
end
