module Encore
  module Helpers
    module ControllerHelper
      HTTP_ERROR_STATUS_CODE = 422
      HTTP_SUCCESS_CODE = 200
      HTTP_SUCCESS_CREATED_CODE = 201

      # Inject itself into the ActionController::Base class
      def self.inject_into_action_controller
        ::ActionController::Base.send :include, self
      end

      # Save the entity and return a JSON response
      def process!(entity)
        error_status = HTTP_ERROR_STATUS_CODE
        success_status = success_status_code_from_entity(entity)

        if entity.save
          render json: entity, status: success_status
        else
          render json: { errors: entity.errors }, status: error_status
        end
      end

    protected

      # Return the status code to send after a successful processing
      # of an entity, depending on its context
      def success_status_code_from_entity(entity)
        case entity.context
          when :create then HTTP_SUCCESS_CREATED_CODE
          else              HTTP_SUCCESS_CODE
        end
      end
    end
  end
end