# frozen_string_literal: true

require 'spec_helper'

RSpec.describe VulnerabilityFeedbackModule::UpdateService, '#execute' do
  let(:group)   { create(:group) }
  let(:project) { create(:project, :public, :repository, namespace: group) }
  let(:user)    { create(:user) }
  let(:pipeline) { create(:ci_pipeline, project: project) }
  let(:vuln_feedback) { create(:vulnerability_feedback, :comment, project: project) }
  let(:service) { described_class.new(project, user, comment: comment) }

  before do
    group.add_developer(user)
  end

  subject(:result) { service.execute(vuln_feedback) }

  context 'when params are valid' do
    context 'when new comment is passed' do
      let(:comment) {'new dismissal comment' }

      let(:vuln_feedback) do
        create(:vulnerability_feedback, :dismissal, :sast,
               project: project,
               author: user,
               pipeline: pipeline)
      end

      it 'adds the comments' do
        expect(result[:status]).to eq(:success)

        feedback = result[:vulnerability_feedback]

        expect(feedback.comment).to eq('new dismissal comment')
        expect(feedback.comment_author).to eq(user)
        expect(feedback.comment_timestamp).not_to be_nil
      end
    end

    context 'second user updates the comment' do
      let(:comment) { 'updated dismissal comment' }
      let(:second_user) { create(:user) }
      let(:service) { described_class.new(project, second_user, vuln_feedback) }

      before do
        group.add_developer(second_user)
      end

      it 'sets second user as the comment author' do
        feedback = result[:vulnerability_feedback]

        expect(feedback.comment_author).to eq(second_user)
      end
    end

    context 'when updated comment is passed' do
      let(:comment) { 'updated dismissal comment' }

      it 'updates the comments' do
        feedback = result[:vulnerability_feedback]

        expect(feedback.comment).to eq('updated dismissal comment')
      end
    end

    context 'when deleting a comment' do
      let(:comment) { '' }

      it 'removes the comment data' do
        expect(result[:status]).to eq(:success)

        feedback = result[:vulnerability_feedback]

        expect(feedback.comment).to be_nil
        expect(feedback.comment_author).to be_nil
        expect(feedback.comment_timestamp).to be_nil
      end
    end
  end
end
