#include <maps/libs/chrono/include/time_point.h>
#include <maps/libs/log8/include/log8.h>
#include <maps/libs/pgpool/include/pgpool3.h>
#include <maps/wikimap/mapspro/services/mrc/libs/config/include/config.h>
#include <maps/wikimap/mapspro/services/mrc/libs/db/include/takeout_data_erasure_gateway.h>
#include <yandex/maps/wiki/common/pgpool3_helpers.h>

#include <cstdint>

namespace {

const auto WARN_HOURS = std::chrono::hours{12};
const auto ERROR_HOURS = std::chrono::hours{24};

}  // 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);
    auto txn = pool.pool().slaveTransaction();

    auto takeoutDataErasure =
        maps::mrc::db::TakeoutDataErasureGateway{*txn}.tryLoadOne(
            maps::mrc::db::table::TakeoutDataErasure::finishedAt.isNull(),
            orderBy(maps::mrc::db::table::TakeoutDataErasure::requestedAt)
                .limit(1));

    if (!takeoutDataErasure) {
        std::cout << "0;Ok: There are no unprocessed tasks" << std::endl;
        return EXIT_SUCCESS;
    }

    const auto lag = std::chrono::duration_cast<std::chrono::hours>(
        maps::chrono::TimePoint::clock::now() -
        takeoutDataErasure->requestedAt());

    if (lag > ERROR_HOURS) {
        std::cout << "2;Error: ";
    }
    else if (lag > WARN_HOURS) {
        std::cout << "1;Warning: ";
    }
    else {
        std::cout << "0;Ok: ";
    }
    std::cout << "The oldest unprocessed task is " << lag.count()
              << " hours old: " << takeoutDataErasure->id() << std::endl;
    return EXIT_SUCCESS;
}
catch (const std::exception& e) {
    std::cout << "2;Error: " << e.what() << std::endl;
    return EXIT_SUCCESS;
}
