# frozen_string_literal: true

module Matterhorn
  module Validator
    def self.included(klass)
      klass.extend ClassMethods
    end

    def valid?
      self.class.validation_methods.each { |name| send(name) }
      return false unless validation_errors.empty?
      true
    end

    def validation_error(name, error)
      validation_errors[name] ||= []
      validation_errors[name].push error
    end

    def validation_errors
      @errors ||= {}
    end

    module ClassMethods
      def validation_rule(name, &validator)
        method_name = :"validate_#{name}"
        define_method method_name do
          unless instance_eval(&validator) == true # check for TrueClass only; other values considered errors
            validation_error(name.to_sym, "Validation failed for #{name}") if validation_errors[name].nil?
            return false
          end
          true
        end
        validation_methods.push method_name
      end

      def validation_methods
        @validation_methods ||= []
      end
    end
  end
end
