#include <maps/wikimap/mapspro/services/social_backoffice/src/api/globals.h>
#include <maps/wikimap/mapspro/services/social/src/libs/yacare/error.h>

#include <yandex/maps/wiki/common/default_config.h>
#include <yandex/maps/wiki/common/extended_xml_doc.h>

#include <maps/libs/log8/include/log8.h>
#include <maps/infra/yacare/include/limit_rate.h>
#include <maps/infra/yacare/include/tvm.h>
#include <maps/infra/yacare/include/yacare.h>

using TvmAlias = NTvmAuth::TClientSettings::TAlias;

namespace {

const TvmAlias TVM_ALIAS = "nmaps-social-backoffice";

} // namespace

yacare::VirtualHost vhost {
    yacare::VirtualHost::SLB { "core-nmaps-social-backoffice" }
};

YCR_SET_DEFAULT(
    vhost,
    yacare::Tvm2ServiceRequire(TVM_ALIAS),
    yacare::LimitRate().resource("maps_core_nmaps_social_backoffice")
);

// The number of seconds before the shutdown to serve requests while not
// responding to /ping.
YCR_OPTIONS.shutdown().grace_period() = 10;

YCR_MAIN(argc, argv) {
    try {
        auto configPtr = argc >= 2
            ? std::make_unique<maps::wiki::common::ExtendedXmlDoc>(argv[1])
            : maps::wiki::common::loadDefaultConfig();

        maps::log8::setLevel(configPtr->get<maps::log8::Level>(
            "/config/log/level", maps::log8::Level::INFO));

        maps::wiki::socialsrv::GlobalsScope globalsScope(*configPtr);

        yacare::setErrorReporter(maps::wiki::socialsrv::errorReporter);
        yacare::run(yacare::RunSettings{.useSystemDefaultLocale = true});

        return EXIT_SUCCESS;
    } catch (const maps::Exception& e) {
        ERROR() << "maps::Exception: " << e;
    } catch (const std::exception& e) {
        ERROR() << "std::exception: " << e.what();
    }
    return EXIT_FAILURE;
}
