#include <maps/wikimap/mapspro/services/mrc/eye/lib/common/include/metadata.h>

#include <maps/libs/log8/include/log8.h>

#include <utility>

namespace maps::mrc::eye {

// MetadataManagerBase
MetadataManagerBase::MetadataManagerBase(std::string name, pqxx::transaction_base& txn)
    : name_(std::move(name))
    , gateway_(txn)
{}

std::string MetadataManagerBase::fullKey(const std::string& key) const { return "eye." + name_ + "." + key; }

const std::string& MetadataManagerBase::name() const { return name_; }

std::string MetadataManagerBase::timeKey() const { return fullKey("time"); }

void MetadataManagerBase::updateTime()
{
    const auto key = timeKey();

    const std::string time = chrono::formatSqlDateTime(chrono::TimePoint::clock::now());
    INFO() << "Update metadata " << key << " " << time;
    gateway().upsertByKey(key, time);
}

std::optional<chrono::TimePoint> MetadataManagerBase::getTime()
{
    const auto time = gateway().tryLoadByKey(timeKey());

    if (not time) {
        return std::nullopt;
    }

    return chrono::parseSqlDateTime(*time);
}

// MetadataManager
MetadataManager::MetadataManager(std::string name, pqxx::transaction_base& txn)
    : MetadataManagerBase(name, txn)
{}

std::string MetadataManager::txnIdKey() const { return fullKey("txn_id"); }

void MetadataManager::updateTxnId(db::TId txnId)
{
    const auto key = txnIdKey();

    INFO() << "Update metadata " << key << " " << txnId;
    gateway().upsertByKey(key, std::to_string(txnId));
}

db::TId MetadataManager::getTxnId() { return gateway().tryLoadByKey<db::TId>(txnIdKey(), 0); }



} // namespace maps::mrc::eye
