# frozen_string_literal: true

class CreateVulnerabilityIssueLinks < ActiveRecord::Migration[5.2]
  DOWNTIME = false

  def change
    create_table :vulnerability_issue_links do |t|
      # index: false because idx_vulnerability_issue_links_on_vulnerability_id_and_issue_id refers the same column
      t.references :vulnerability, null: false, index: false, foreign_key: { on_delete: :cascade }
      # index: true is implied
      t.references :issue, null: false, foreign_key: { on_delete: :cascade }
      t.integer 'link_type', limit: 2, null: false, default: 1 # 'related'
      t.index %i[vulnerability_id issue_id],
              name: 'idx_vulnerability_issue_links_on_vulnerability_id_and_issue_id',
              unique: true # only one link (and of only one type) is allowed
      t.index %i[vulnerability_id link_type],
              name: 'idx_vulnerability_issue_links_on_vulnerability_id_and_link_type',
              where: 'link_type = 2',
              unique: true # only one 'created' link per vulnerability is allowed
      t.timestamps_with_timezone
    end
  end
end
