#include <maps/libs/log8/include/log8.h>
#include <maps/wikimap/mapspro/services/mrc/libs/config/include/config.h>
#include <maps/wikimap/mapspro/services/mrc/libs/juggler/include/juggler.h>
#include <maps/wikimap/mapspro/services/mrc/long_tasks/excess_features_eraser/lib/db.h>

namespace {

maps::mrc::juggler::Message checkLastRunTime(pqxx::transaction_base& txn)
{
    constexpr auto WARN_LAG = std::chrono::hours{30};
    constexpr auto ERROR_LAG = 2 * WARN_LAG;

    auto lastSuccessRunTime =
        maps::mrc::excess_features_eraser::loadLastRunTime(txn);
    if (!lastSuccessRunTime) {
        return maps::mrc::juggler::error("the process has never been run");
    }
    auto runLag = std::chrono::duration_cast<std::chrono::hours>(
        maps::chrono::TimePoint::clock::now() - *lastSuccessRunTime);
    auto 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().slaveTransaction());
    return EXIT_SUCCESS;
}
catch (const std::exception& e) {
    std::cout << maps::mrc::juggler::error(e.what());
    return EXIT_SUCCESS;
}
