#include "connection_manager.h"

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

namespace maps::wiki::aclsrv {

std::unique_ptr<common::PoolHolder> ConnectionManager::s_poolHolder;

ConnectionManager::ConnectionManager(const std::string& filepath, const std::string& srvName)
{
    auto overrideConstants = [](pgpool3::PoolConstants p) {
        p.treatMasterAsSlave = true;
        return p;
    };

    common::ExtendedXmlDoc doc(filepath);
    REQUIRE(!s_poolHolder, "ConnectionManager already initialized.");
    s_poolHolder = std::make_unique<common::PoolHolder>(overrideConstants, doc, srvName, srvName);
}

ConnectionManager::~ConnectionManager()
{
    s_poolHolder.reset();
}

maps::pgpool3::TransactionHandle
ConnectionManager::slaveTransaction(const std::string& token)
{
    REQUIRE(s_poolHolder, "ConnectionManager not initialized.");
    return s_poolHolder->pool().slaveTransaction(token);
}

maps::pgpool3::TransactionHandle
ConnectionManager::masterWriteableTransaction(acl::UID authorUid)
{
    REQUIRE(s_poolHolder, "ConnectionManager not initialized.");
    auto txn = s_poolHolder->pool().masterWriteableTransaction();
    txn->exec("SELECT acl.setCurrentUid(" + std::to_string(authorUid) + ");");
    return txn;
}

} // namespace maps::wiki::aclsrv
