module VersionRecord
  extend ActiveSupport::Concern

  DEFAULT_EVENT_TYPE_MAP = { create: 'create',
                             update: 'update',
                             discard: 'discard',
                             restore: 'restore' }.freeze

  def readonly? = persisted?

  included do
    event_type_map = if const_defined?(:EVENT_TYPE_MAP, false)
                       const_get(:EVENT_TYPE_MAP)
                     else
                       DEFAULT_EVENT_TYPE_MAP
                     end

    belongs_to :created_by_user, class_name: 'User', optional: true

    enum :event_type, event_type_map, prefix: true, validate: true

    validates :version_no, presence: true, numericality: { only_integer: true, greater_than: 0 }
    validates :event_type, presence: true

    scope :chronological, -> { order(:version_no, :id) }
  end
end
