# frozen_string_literal: true

require 'spec_helper'
require_migration!

RSpec.describe MigrateVulnerabilityDismissalFeedback, :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(:dismissed_state) { Gitlab::BackgroundMigration::UpdateVulnerabilitiesFromDismissalFeedback::VULNERABILITY_DISMISSED_STATE }
  let(:severity) { Vulnerabilities::Finding::SEVERITY_LEVELS[:unknown] }
  let(:confidence) { Vulnerabilities::Finding::CONFIDENCE_LEVELS[:medium] }
  let(:report_type) { Vulnerabilities::Finding::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 UpdateVulnerabilitiesFromDismissalFeedback migration' do
      expect(BackgroundMigrationWorker).to receive(:perform_in).with(0, 'UpdateVulnerabilitiesFromDismissalFeedback', project_1.id )
      expect(BackgroundMigrationWorker).to receive(:perform_in).with(120, 'UpdateVulnerabilitiesFromDismissalFeedback', 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: dismissed_state,
      severity: severity,
      confidence: confidence,
      report_type: report_type,
      author_id: user.id
    }
  end
end
