# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Banzai::ReferenceParser::VulnerabilityParser do
  include ReferenceParserHelpers

  def link(vulnerability_id)
    link = empty_html_link
    link['data-vulnerability'] = vulnerability_id.to_s
    link
  end

  let(:user)             { create(:user) }
  let(:public_project)   { create(:project, :public) }
  let(:private_project1) { create(:project, :private) }
  let(:private_project2) { create(:project, :private) }
  let(:vulnerability)    { create(:vulnerability, project: public_project) }
  let(:vulnerability1)   { create(:vulnerability, project: private_project1) }
  let(:vulnerability2)   { create(:vulnerability, project: private_project2) }
  let(:nodes) do
    [link(vulnerability.id), link(vulnerability1.id), link(vulnerability2.id)]
  end

  subject { described_class.new(Banzai::RenderContext.new(nil, user)) }

  describe '#nodes_visible_to_user' do
    before do
      private_project1.add_developer(user)
    end

    context 'when the vulnerabilities feature is enabled' do
      before do
        stub_licensed_features(security_dashboard: true)
      end

      it 'returns the nodes the user can read for valid vulnerability nodes' do
        expected_result = [nodes[1]]

        expect(subject.nodes_visible_to_user(user, nodes)).to match_array(expected_result)
      end

      it 'returns an empty array for nodes without required data-attributes' do
        expect(subject.nodes_visible_to_user(user, [empty_html_link])).to be_empty
      end
    end

    context 'when the vulnerabilities feature is disabled' do
      it 'returns an empty array' do
        expect(subject.nodes_visible_to_user(user, nodes)).to be_empty
      end
    end
  end

  describe '#referenced_by' do
    context 'when using an existing vulnerabilities IDs' do
      it 'returns an Array of vulnerabilities' do
        expected_result = [vulnerability, vulnerability1, vulnerability2]

        expect(subject.referenced_by(nodes)).to match_array(expected_result)
      end

      it 'returns an empty Array for empty list of nodes' do
        expect(subject.referenced_by([])).to be_empty
      end
    end

    context 'when vulnerability with given ID does not exist' do
      it 'returns an empty Array' do
        expect(subject.referenced_by([link(non_existing_record_id)])).to be_empty
      end
    end
  end

  describe '#records_for_nodes' do
    it 'returns a Hash containing the vulnerabilities for a list of nodes' do
      expected_hash = {
        nodes[0] => vulnerability,
        nodes[1] => vulnerability1,
        nodes[2] => vulnerability2
      }
      expect(subject.records_for_nodes(nodes)).to eq(expected_hash)
    end
  end
end
