# frozen-string-literal: true

require 'navigable/immutable_object'
require 'navigable/errors'

module Navigable
  class Input < ImmutableObject
    class << self
      def validates_presence_of(field)
        validations << ->(subject) do
          if subject.public_send(field).nil?
            subject.errors.add(field, "not present")
          end
        end
      end
      
      def validates_max_length_of(field, max_length)
        validations << ->(subject) do
          if (subject.public_send(field) && subject.public_send(field).length > max_length)
            subject.errors.add(field, "longer than #{max_length}")
          end
        end
      end

      def validations
        @validations ||= []
      end
    end

    attr_reader :errors

    def initialize(attributes = {})
      @errors = Errors.new
      super(**attributes.to_hash.transform_keys(&:to_sym))
    end

    def valid?
      self.class.validations.each { |validation| validation.call(self) }
      @errors.empty?
    end
  end
end
