#include <libfilezilla/logger.hpp>

#include "password_with_impersonation.hpp"

namespace fz::authentication::password {

bool with_impersonation::verify(std::string_view password, impersonation_context &impersonation, logger_interface &logger) const
{
	if (auto i = get_impersonation()) {
		logger.log_u(logmsg::debug_debug, L"Trying to get impersonation token for user [%s].", impersonation.username);

		if (impersonation.token) {
			logger.log_raw(logmsg::error, L"password::with_impersonation conflict: we already have an impersonation token, and there can be only one.");
			return false;
		}

		impersonation_token t(impersonation.username, fz::to_native(password), logger);

		logger.log_u(logmsg::debug_verbose, L"impersonation_token: { username: \"%s\", home: \"%s\", uid: \"%s\" }", t.username(), t.home(), t.uid());

		if (t) {
			impersonation.username = t.username();
			impersonation.home = t.home();

			if (!i->login_only) {
				impersonation.token = std::move(t);
			}

			return true;
		}

		return false;
	}

	if (get()) {
		return password_.verify(password);
	}

	return false;
}

}
