#include <yandex/maps/wiki/unittest/arcadia.h>

#include <yandex/maps/wiki/unittest/default_extensions.h>
#include "util.h"

namespace maps::wiki::unittest {

namespace {

local_postgres::Database initTemplateDatabase()
{
    local_postgres::Database database;
    for (const auto& ext : defaultPsqlExtensions()) {
        database.createExtension(ext);
    }
    database.runPgMigrate(DEFAULT_MAPSPRO_DB_MIGRATIONS_PATH);
    return database;
}

local_postgres::Database& getTemplateDatabase()
{
    static auto database = initTemplateDatabase();
    return database;
}

} // namespace

local_postgres::Database& ArcadiaDbFixture::database()
{
    if (!database_) {
        database_ = std::make_unique<local_postgres::Database>(
            getTemplateDatabase().clone());
    }
    return *database_;
}

pgpool3::Pool& ArcadiaDbFixture::pool()
{
    if (!pool_) {
        auto constants = pgpool3::PoolConstants(10, 20, 10, 20);
        constants.getTimeoutMs = std::chrono::seconds(15);
        constants.timeoutEarlyOnMasterUnavailable = false;

        pool_ = std::make_unique<pgpool3::Pool>(
            connectionString(),
            std::move(constants));
    }

    return *pool_;
}

std::string ArcadiaDbFixture::connectionString()
{
    return database().connectionString();
}

void ArcadiaDbFixture::executeSqlInTransaction(const std::string& sql)
{
    auto txn = pool().masterWriteableTransaction();
    txn->exec(sql);
    txn->commit();
}

} // maps::wiki::unittest
