module VulnerabilityFeedbackModule
  class CreateService < ::BaseService
    def execute
      vulnerability_feedback = @project.vulnerability_feedback.new(@params)
      vulnerability_feedback.author = @current_user

      # Wrap Feedback and Issue creation in the same transaction
      ActiveRecord::Base.transaction do
        if vulnerability_feedback.issue? && # (feedback_type == 'issue')
            !vulnerability_feedback.vulnerability_data.blank?

          result = Issues::CreateFromVulnerabilityDataService
            .new(@project, @current_user, vulnerability_feedback.vulnerability_data)
            .execute

          if result[:status] == :error
            vulnerability_feedback.errors[:issue] << result[:message]
            raise ActiveRecord::Rollback
          end

          issue = result[:issue]
          vulnerability_feedback.issue = issue
        end

        # Ensure created issue is rolled back if feedback can't be saved
        raise ActiveRecord::Rollback unless vulnerability_feedback.save
      end

      if vulnerability_feedback.persisted?
        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 success(vulnerability_feedback)
      super().merge(vulnerability_feedback: vulnerability_feedback)
    end
  end
end
