# frozen_string_literal: true

require 'zlib'

module Gitlab
  class Experiment
    module Rollout
      class Percent < Base
        def execute
          crc = normalized_id
          total = 0

          case distribution_rules
          # run through the rules until finding an acceptable one
          when Array then variant_names[distribution_rules.find_index { |percent| crc % 100 <= total += percent }]
          # run through the variant names until finding an acceptable one
          when Hash then distribution_rules.find { |_, percent| crc % 100 <= total += percent }.first
          # when there are no rules, assume even distribution
          else variant_names[crc % variant_names.length]
          end
        end

        def validate!
          case distribution_rules
          when nil then nil
          when Array, Hash
            if distribution_rules.length != variant_names.length
              raise InvalidRolloutRules, "the distribution rules don't match the number of variants defined"
            end
          else
            raise InvalidRolloutRules, 'unknown distribution options type'
          end
        end

        private

        def normalized_id
          Zlib.crc32(id, nil)
        end

        def distribution_rules
          @options[:distribution]
        end
      end
    end
  end
end
