require 'ostruct'

module ThreeScale
  module Analytics
    class UserClassifier
      THREESCALE_EMAIL_REGEX =%r{
        @(3scale\.net
         |3scalesolutions\.com
         |3scale\.ws
         |3scale\.com
         |apicast\.io
         |3scalesolutions\.net
         )$
      }xi.freeze

      THREESCALE_ADMIN = '3scaleadmin'.freeze
      EMPTY_USER = OpenStruct.new(email: nil, username: nil).freeze

      def self.classify(user)
        new(user).user_type
      end

      def initialize(user)
        @user = user || EMPTY_USER
      end

      def has_3scale_email?
        THREESCALE_EMAIL_REGEX.match(@user.email.to_s)
      end

      def is_3scaleadmin?
        @user.username == THREESCALE_ADMIN
      end

      def is_3scale?
        has_3scale_email? || is_3scaleadmin?
      end

      def is_guest?
        @user.username.nil? || @user.email.nil?
      end

      def user_type
        case
        when is_guest? then 'guest'.freeze
        when is_3scale? then '3scale'.freeze
        else 'customer'.freeze
        end
      end
    end
  end
end
