#include <maps/wikimap/mapspro/services/mrc/libs/config/include/config.h>
#include <maps/wikimap/mapspro/services/mrc/long_tasks/import_nexar/lib/metadata.h>
#include <maps/wikimap/mapspro/services/mrc/libs/juggler/include/juggler.h>
#include <yandex/maps/wiki/common/pgpool3_helpers.h>
#include <maps/libs/log8/include/log8.h>
#include <maps/libs/pgpool/include/pgpool3.h>
#include <maps/libs/chrono/include/time_point.h>

#include <cstdint>
#include <pqxx/transaction_base>

namespace {

maps::mrc::juggler::Message
checkLastRunTime(pqxx::transaction_base& txn)
{
    constexpr std::chrono::hours WARN_LAG{24};
    constexpr std::chrono::hours ERROR_LAG{48};

    auto metadata = maps::mrc::import_nexar::loadMetadata(txn);
    if (!metadata.lastSuccessRunTime().has_value()) {
        return maps::mrc::juggler::error("The process has never been run");
    }
    const auto now = maps::chrono::TimePoint::clock::now();
    const auto runLag = std::chrono::duration_cast<std::chrono::hours>(
        now - metadata.lastSuccessRunTime().value());

    const std::string durationSinceLastRunMessage =
        "last run was " + std::to_string(runLag.count()) + " hours ago";

    if (runLag > ERROR_LAG) {
        return maps::mrc::juggler::error(durationSinceLastRunMessage);
    } else if (runLag > WARN_LAG) {
        return maps::mrc::juggler::warn(durationSinceLastRunMessage);
    } else {
        return maps::mrc::juggler::ok(durationSinceLastRunMessage);
    }
}

}  // namespace

int main()
try {
    maps::log8::setLevel(maps::log8::Level::FATAL);
    auto cfg = maps::mrc::common::templateConfig();
    auto pool = cfg.makePoolHolder(maps::mrc::common::LONG_READ_DB_ID,
                                   maps::mrc::common::LONG_READ_POOL_ID);

    std::cout << checkLastRunTime(*pool.pool().masterReadOnlyTransaction());
    return EXIT_SUCCESS;
}
catch (const std::exception& e) {
    std::cout << maps::mrc::juggler::error(e.what());
    return EXIT_SUCCESS;
}
