module Hippo::Concerns

    # @see ClassMethods
    module RandomIdentifer

        extend ActiveSupport::Concern

        # ### Random Identifier Concern
        # This adds the {#has_random_hash_code} class method
        module ClassMethods

            # A random string that identifies an model
            # The code is generated by {Hippo::Strings.random} for new records
            # It's useful for generating links for anonymous access to an entity that cannot be guessed.
            # @param field_name [Symbol] which field should the hash_code be stored in
            # @param length [Integer] how long the hash_code should be

            def has_random_identifier(field_name: :identifier, length: 12)

                validates field_name,
                          presence: {
                              message: "random identifier is not set (should be automatically chosen)"
                          }

                before_validation(on: :create) do
                    5.times do
                        if self[field_name].blank?
                            code = Hippo::Strings.random(length)
                            self[field_name] = code if self.class.where("#{field_name}" => code).none?
                        end
                        break if self[field_name].present?
                    end
                end
            end
        end
    end
end
