# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Security::Ingestion::Tasks::IngestVulnerabilityFlags do
  describe '#execute' do
    let_it_be(:pipeline) { create(:ci_pipeline) }

    let(:vulnerability_finding) { create(:vulnerabilities_finding) }
    let!(:existing_vulnerability_flag_1) { create(:vulnerabilities_flag, origin: 'post analyzer 1', finding: vulnerability_finding) }
    let!(:existing_vulnerability_flag_2) { create(:vulnerabilities_flag, origin: 'post analyzer 2', finding: vulnerability_finding, description: 'foo') }

    let(:report_finding_flag_2) { create(:ci_reports_security_flag, origin: 'post analyzer 2', description: 'bar') }
    let(:report_finding_flag_3) { create(:ci_reports_security_flag, origin: 'post analyzer 3') }
    let(:report_finding_flag_4) { create(:ci_reports_security_flag, origin: 'post analyzer 4') }

    let(:report_finding) { create(:ci_reports_security_finding, flags: [report_finding_flag_2, report_finding_flag_3, report_finding_flag_4]) }
    let(:finding_map) { create(:finding_map, finding: vulnerability_finding, report_finding: report_finding) }
    let(:service_object) { described_class.new(pipeline, [finding_map]) }

    subject(:ingest_vulnerability_flags) { service_object.execute }

    it 'creates new records and updates the existing ones' do
      expect { ingest_vulnerability_flags }.to change { vulnerability_finding.vulnerability_flags.count }.from(2).to(3)
                                           .and change { existing_vulnerability_flag_2.reload.description }.from('foo').to('bar')
    end

    it 'deletes the old records' do
      expect { ingest_vulnerability_flags }.to change { Vulnerabilities::Flag.find_by_id(existing_vulnerability_flag_1.id) }.to(nil)
    end
  end
end
