module Support
  class User
    attr_reader :info, :name

    def initialize(name:, domain:, user_data:)
      @name = name
      @info = user_data
      @feature_flags = {}
      @orchard_user_id = build_orchard_user_id(domain)
      @orchard_vendor_id = build_vendor_id(domain)
      @subscriptions = {}
    end

    def check_user_features
      @feature_flags = Services::OwsFeatures.get_user_features(@orchard_user_id)
    end

    def active_variant_for_feature(feature_name)
      known_variant = @feature_flags[feature_name]
      return known_variant if known_variant
      active_variant = Services::OwsFeatures.active_variant_for_user(
        feature_name, @orchard_user_id
      )
      @feature_flags[feature_name] = active_variant
    end

    def feature_variance_enabled?(feature_name)
      active_variant = Services::OwsFeatures.active_variant_for_user(
        feature_name, @orchard_user_id
      )
      active_variant == "enabled"
    end

    def update_active_variant_for_feature(feature_name, new_variant)
      # if a scenario explicitly sets the active variant for a feature, then
      # that means the scenario is specifically testing the scenario with that
      # active variant.
      # since the active variants can (and often do) change mid-test due to
      # other tests, this means that we need to store set variants instead of
      # just calling ows-features every time.
      case new_variant
      when "enabled"
        SplitIOClient.add_user_to_split(@orchard_user_id.to_s, feature_name)
      else
        fail "unknown command: '#{new_variant}'!"
      end
      @feature_flags[feature_name] = new_variant
    end

    def check_user_subscriptions(account_type)
      @subscriptions = Services::OwsNotifications.get_subscriptions(
        @orchard_user_id,
        @orchard_vendor_id,
        account_type
      )
    end

    private

    def build_orchard_user_id(domain)
      case domain
      when :workstation
        "alw:#{@info[:vend_contact_id]}"
      when :oa
        "oa:#{@info[:id]}"
      else
        fail "unknown user domain: '#{domain}'!"
      end
    end

    def build_vendor_id(domain)
      case domain
      when :workstation
        @info[:id]
      end
    end
  end
end
