# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::DataBuilder::Vulnerability do
  let(:trait) { :sast }
  let(:artifact) { create(:ee_ci_job_artifact, trait) }
  let(:report_type) { artifact.file_type }
  let(:project) { artifact.project }
  let(:pipeline) { artifact.job.pipeline }
  let(:report) { pipeline.security_reports.get_report(report_type.to_s, artifact) }

  let(:finding_identifier_fingerprint) do
    build(:ci_reports_security_identifier, external_id: "CIPHER_INTEGRITY").fingerprint
  end

  let(:scanner) { build(:vulnerabilities_scanner, project: project, external_id: 'find_sec_bugs', name: 'Find Security Bugs') }
  let(:identifier) { build(:vulnerabilities_identifier, project: project, fingerprint: finding_identifier_fingerprint) }
  let(:finding_location_fingerprint) do
    build(
      :ci_reports_security_locations_sast,
      file_path: "groovy/src/main/java/com/gitlab/security_products/tests/App.groovy",
      start_line: "29",
      end_line: "29"
    ).fingerprint
  end

  let(:finding) do
    build(:vulnerabilities_finding,
          :with_pipeline,
          identifiers: [identifier],
          primary_identifier: identifier,
          scanner: scanner,
          project: project,
          uuid: "e5388f40-18f5-566d-95c6-d64c6f46a00a",
          location_fingerprint: finding_location_fingerprint
         )
  end

  let(:vulnerability) { create(:vulnerability, findings: [finding], project: project) }

  describe '.build' do
    let(:data) { described_class.build(vulnerability) }

    it { expect(data).to be_a(Hash) }
    it { expect(data[:object_kind]).to eq('vulnerability') }

    it 'contains the correct object attributes', :aggregate_failures do
      object_attributes = data[:object_attributes]
      expected_attributes = {
        url: ::Gitlab::Routing.url_helpers.project_security_vulnerability_url(vulnerability.project, vulnerability),
        title: vulnerability.title,
        state: vulnerability.state,
        severity: vulnerability.severity,
        severity_overridden: vulnerability.severity_overridden,
        report_type: vulnerability.report_type,
        confidence: vulnerability.confidence,
        confidence_overridden: vulnerability.confidence_overridden,
        dismissed_at: vulnerability.dismissed_at,
        dismissed_by_id: vulnerability.dismissed_by_id,
        identifiers: [
          {
            name: identifier.name,
            external_id: identifier.external_id,
            external_type: identifier.external_type,
            url: identifier.url
          }
        ]
      }

      expect(object_attributes).to eq(expected_attributes)
    end
  end
end
