# frozen_string_literal: true

require 'spec_helper'
require Rails.root.join('db', 'post_migrate', '20200821224343_schedule_populate_vulnerability_historical_statistics.rb')

RSpec.describe SchedulePopulateVulnerabilityHistoricalStatistics do
  let(:users) { table(:users) }
  let(:namespaces) { table(:namespaces) }
  let(:vulnerabilities) { table(:vulnerabilities) }
  let(:projects) { table(:projects) }
  let(:namespace) { namespaces.create!(name: 'gitlab', path: 'gitlab-org') }
  let(:user) { users.create!(name: 'test', email: 'test@example.com', projects_limit: 5) }

  def create_project(id, with_vulnerabilities: false)
    project_params = {
      id: id,
      namespace_id: namespace.id,
      name: 'foo'
    }

    project = projects.create!(project_params)
    return unless with_vulnerabilities

    vulnerabilities.create!(title: 'title', state: 1, severity: 0, confidence: 5, report_type: 2, project_id: project.id, author_id: user.id)
  end

  it 'correctly schedules background migrations with projects with vulnerabilities only', :aggregate_failures do
    create_project(1, with_vulnerabilities: true)
    create_project(2, with_vulnerabilities: true)
    create_project(5, with_vulnerabilities: false)
    create_project(6, with_vulnerabilities: false)

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

    Sidekiq::Testing.fake! do
      freeze_time do
        migrate!

        expect(described_class::MIGRATION)
          .to be_scheduled_delayed_migration(2.minutes, [1])

        expect(described_class::MIGRATION)
          .to be_scheduled_delayed_migration(4.minutes, [2])

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

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

    it 'does not schedule any jobs' do
      create_project(2)

      Sidekiq::Testing.fake! do
        freeze_time do
          migrate!

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