# frozen_string_literal: true

module VulnerabilityFeedbackModule
  class UpdateService < ::BaseService
    def execute(vulnerability_feedback)
      raise Gitlab::Access::AccessDeniedError unless can?(current_user, :update_vulnerability_feedback, vulnerability_feedback)

      if vulnerability_feedback.update(vulnerability_feedback_attributes)
        success(vulnerability_feedback)
      else
        error(vulnerability_feedback.errors)
      end

    rescue ArgumentError => e
      # VulnerabilityFeedback relies on #enum attributes which raise this exception
      error(e.message)
    end

    private

    def vulnerability_feedback_attributes
      if params[:comment].present?
        { comment: params[:comment], comment_timestamp: Time.zone.now, comment_author: current_user }
      else
        { comment: nil, comment_timestamp: nil, comment_author: nil }
      end
    end

    def success(vulnerability_feedback)
      super().merge(vulnerability_feedback: vulnerability_feedback)
    end
  end
end
