require 'test_helper'

class Users::FindOauth2UserServiceTest < ActiveSupport::TestCase

  class UsersDouble; end

  def test_run
    service.any_instance.expects(:find).returns(true)
    assert service.run({}, {}, [])
  end

  def test_find
    user = User.new

    service.any_instance.expects(:find_by_sso_authorization).returns(user).once
    service.any_instance.expects(:find_by_authentication_id).never
    service.any_instance.expects(:find_by_email).never
    assert_equal user, service.run({}, {}, [])

    service.any_instance.expects(:find_by_sso_authorization).returns(nil).once
    service.any_instance.expects(:find_by_authentication_id).returns(user)
    service.any_instance.expects(:find_by_email).never
    assert_equal user, service.run({}, {}, [])

    service.any_instance.expects(:find_by_sso_authorization).returns(nil).once
    service.any_instance.expects(:find_by_authentication_id).returns(nil).once
    service.any_instance.expects(:find_by_email).returns(user).once
    assert_equal user, service.run({}, {}, [])
  end

  def test_find_by_email
    users = UsersDouble.new
    users.expects(:find_by).with(email: 'alaska@wild.com').never
    service.any_instance.expects(:find_by_uid).returns(nil).at_least_once
    service.run({}, {}, users)

    users.expects(:find_by).with(email: 'alaska@wild.com').never
    service.run({ email: 'alaska@wild.com' }, {}, users)

    users.expects(:find_by).with(email: 'alaska@wild.com').once
    service.run({ email_confirmed: true, email: 'alaska@wild.com' }, {}, users)
  end

  def test_find_by_sso_authorization
    SsoAuthorization.expects(:find_by).never
    service.run({}, {}, [])

    SsoAuthorization.expects(:find_by).once
    service.run({ uid: 'alaska' }, {}, [])
  end

  def test_find_by_authentication_id
    users = UsersDouble.new
    users.expects(:find_by).with(authentication_id: 'alaska').never
    service.any_instance.expects(:find_by_sso_authorization).returns(nil).at_least_once
    service.run({}, {}, users)

    users.expects(:find_by).with(authentication_id: 'alaska').once
    service.run({ authentication_id: 'alaska' }, {}, users)
  end

  private

  def service
    Users::FindOauth2UserService
  end
end
