# frozen_string_literal: true

require 'active_support/callbacks'

module Gitlab
  class Experiment
    module Callbacks
      extend ActiveSupport::Concern
      include ActiveSupport::Callbacks

      included do
        define_callbacks(:run)
        define_callbacks(:unsegmented)
        define_callbacks(:segmentation_check)
        define_callbacks(:exclusion_check, skip_after_callbacks_if_terminated: true)
      end

      class_methods do
        private

        def build_callback(chain, filters, **options)
          filters = filters.compact.map do |filter|
            result_lambda = ActiveSupport::Callbacks::CallTemplate.build(filter, self).make_lambda
            ->(target) { yield(target, result_lambda) }
          end

          raise ArgumentError, 'no filters provided' if filters.empty?

          set_callback(chain, *filters, **options)
        end
      end
    end
  end
end
