class Users::FindOauth2UserService

  def self.run(oauth_data, auth_provider, scoped_users)
    new(oauth_data, auth_provider, scoped_users).find
  end

  def initialize(oauth_data, auth_provider, scoped_users)
    @uid = oauth_data[:uid]
    @authentication_id = oauth_data[:authentication_id]
    @confirmed_email = oauth_data[:email_confirmed] && oauth_data[:email]
    @auth_provider = auth_provider
    @scoped_users = scoped_users
  end

  def find
    find_by_uid || find_by_email
  end

  private

  def find_by_email
    return if confirmed_email.blank?
    scoped_users.find_by(email: confirmed_email)
  end

  def find_by_uid
    find_by_sso_authorization || find_by_authentication_id
  end

  def find_by_sso_authorization
    return if uid.blank?
    SsoAuthorization.find_by(authentication_provider: auth_provider,
      uid: uid, user: scoped_users).try(:user)
  end

  def find_by_authentication_id
    return if authentication_id.blank?
    scoped_users.find_by(authentication_id: authentication_id)
  end

  attr_reader :uid, :authentication_id, :confirmed_email, :auth_provider, :scoped_users
end
