#include <maps/wikimap/mapspro/services/mrc/long_tasks/regular_upload/lib/include/tools.h>

#include <maps/libs/log8/include/log8.h>
#include <maps/libs/chrono/include/time_point.h>
#include <maps/wikimap/mapspro/services/mrc/libs/db/include/metadata_gateway.h>

#include <yandex/maps/wiki/common/pgpool3_helpers.h>

#include <string>


namespace maps::mrc::regular_upload {

const std::string APP_NAME = "regular_upload";
const std::string LAST_RUN_TIME = APP_NAME + ".timestamp";

std::optional<maps::chrono::TimePoint> getLastRunTime(pgpool3::TransactionHandle txn)
{
    auto timeStr = db::MetadataGateway{*txn}.tryLoadByKey(LAST_RUN_TIME);
    if (timeStr) {
        return maps::chrono::parseSqlDateTime(*timeStr);
    }
    return std::nullopt;
}

void setLastRunTime(pgpool3::TransactionHandle txn)
{
    INFO() << "Updating metadata";
    db::MetadataGateway{*txn}.upsertByKey(
        LAST_RUN_TIME,
        maps::chrono::formatSqlDateTime(maps::chrono::TimePoint::clock::now()));

    txn->commit();
}

} //namespace maps::mrc::regular_upload
