# frozen_string_literal: true

require 'spec_helper'

RSpec.describe VulnerabilityExports::CreateService do
  include AccessMatchersGeneric

  before do
    stub_licensed_features(security_dashboard: true)
  end

  let_it_be(:user) { create(:user, :auditor) }

  let(:group) { create(:group) }
  let(:project) { create(:project, :public, group: group) }
  let(:format) { 'csv' }

  subject(:create_export) { described_class.new(project, user, format: format).execute }

  describe '#execute' do
    context 'when security dashboard feature is disabled' do
      before do
        stub_licensed_features(security_dashboard: false)
      end

      it 'raises an "access denied" error' do
        expect { create_export }.to raise_error(Gitlab::Access::AccessDeniedError)
      end
    end

    context 'when security dashboard feature is enabled' do
      let(:recent_vulnerability_export) { Vulnerabilities::Export.last }

      before do
        allow(::VulnerabilityExports::ExportWorker).to receive(:perform_async)
      end

      it 'does not raise an "access denied" error' do
        expect { create_export }.not_to raise_error
      end

      it 'creates new Vulnerabilities::Export' do
        expect { create_export }.to change { Vulnerabilities::Export.count }.from(0).to(1)
      end

      it 'schedules ::VulnerabilityExports::ExportWorker background job' do
        create_export

        expect(::VulnerabilityExports::ExportWorker).to have_received(:perform_async).with(recent_vulnerability_export.id)
      end

      it 'returns new Vulnerabilities::Export with project and format assigned' do
        expect(create_export).to have_attributes(project_id: project.id, format: format)
      end
    end
  end
end
