# frozen_string_literal: true

require 'spec_helper'
require_migration!

RSpec.describe MigrateVulnerabilityDismissals, :migration, :sidekiq do
  let(:users) { table(:users) }
  let(:namespaces) { table(:namespaces) }
  let(:projects) { table(:projects) }

  let!(:user) { users.create!(id: 13, email: 'author@example.com', username: 'author', projects_limit: 10) }
  let(:namespace) { namespaces.create!(name: 'gitlab', path: 'gitlab-org') }
  let(:project_1) { projects.create!(name: 'gitlab', path: 'gitlab-ce', namespace_id: namespace.id) }
  let(:project_2) { projects.create!(name: 'gitlab2', path: 'gitlab-ce', namespace_id: namespace.id) }

  let(:vulnerabilities) { table(:vulnerabilities) }

  let(:detected_state) {  Gitlab::BackgroundMigration::UpdateVulnerabilitiesToDismissed::VULNERABILITY_DETECTED }
  let(:severity) { ::Enums::Vulnerability.severity_levels[:unknown] }
  let(:confidence) { ::Enums::Vulnerability.confidence_levels[:medium] }
  let(:report_type) { ::Enums::Vulnerability.report_types[:sast] }

  before do
    stub_const("#{described_class.name}::BATCH_SIZE", 1)

    vulnerabilities.create!(vuln_params.merge!({ project_id: project_1.id }) )
    vulnerabilities.create!(vuln_params.merge!({ project_id: project_2.id }) )
    vulnerabilities.create!(vuln_params.merge!({ project_id: project_2.id }) )
  end

  context 'EE' do
    before do
      allow(Gitlab).to receive(:ee?).and_return(true)
    end

    it 'creates background job for each project' do
      migrate!

      expect(BackgroundMigrationWorker.jobs.size).to eq 2
    end

    it 'calls the UpdateVulnerabilitiesToDismissed migration' do
      expect(BackgroundMigrationWorker).to receive(:perform_in).with(0, 'UpdateVulnerabilitiesToDismissed', project_1.id )
      expect(BackgroundMigrationWorker).to receive(:perform_in).with(120, 'UpdateVulnerabilitiesToDismissed', project_2.id )

      migrate!
    end
  end

  context 'FOSS' do
    before do
      allow(Gitlab).to receive(:ee?).and_return(false)
    end

    it 'skips migration for FOSS' do
      Sidekiq::Testing.fake! do
        migrate!

        expect(BackgroundMigrationWorker.jobs.size).to eq 0
      end
    end
  end

  def vuln_params
    {
      title: 'title',
      state: detected_state,
      severity: severity,
      confidence: confidence,
      report_type: report_type,
      author_id: user.id
    }
  end
end
