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

namespace maps::mrc::eye {

using RepeatableReadTxn = pqxx::transaction<pqxx::repeatable_read>;

pgpool3::TransactionHandle getMasterWriteTxn(pgpool3::Pool& pool)
{
    auto connection = pool.getMasterConnection();

    return {
        std::move(connection),
        std::make_unique<RepeatableReadTxn>(connection.get())
    };
}

pgpool3::TransactionHandle getSlaveTxn(pgpool3::Pool& pool, std::string token)
{
    auto connection = pool.getSlaveConnection(token);

    return {
        std::move(connection),
        std::make_unique<RepeatableReadTxn>(connection.get())
    };
}

std::string getNewToken(pgpool3::Pool& pool)
{
    auto txn = pool.masterReadOnlyTransaction();
    return pgpool3::generateToken(*txn);
}

std::string commit(pqxx::transaction_base& txn)
{
    std::string token = pgpool3::generateToken(txn);
    txn.commit();
    return token;
}

} // namespace maps::mrc::eye
