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

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

#include "util.h"

using namespace std::chrono_literals;

namespace maps {
namespace wiki {
namespace unittest {

namespace {

constexpr size_t MASTER_SIZE = 4;
constexpr size_t MASTER_MAX_SIZE = 10;
constexpr size_t SLAVE_SIZE = 6;
constexpr size_t SLAVE_MAX_SIZE = 15;
constexpr auto GET_TIMEOUT_MS = 15s;
constexpr auto PING_INTERVAL_MS = 1s;

} //anonymous namespace

/*****************************************************************************/
/*               R A N D O M   D A T A B A S E   F I X T U R E               */
/*****************************************************************************/
RandomDatabaseFixture::RandomDatabaseFixture()
    : database_()
    , pool_(createPool())
    , connectionString_(database_.connectionString())
{
    for (const auto& ext : maps::wiki::unittest::defaultPsqlExtensions()) {
        database_.createExtension(ext);
    }
}

pgpool3::Pool& RandomDatabaseFixture::pool()
{
    return pool_;
}

const std::string& RandomDatabaseFixture::host() const
{
    return database_.host();
}

uint16_t RandomDatabaseFixture::port() const
{
    return database_.port();
}

const std::string& RandomDatabaseFixture::dbname() const
{
    return database_.dbname();
}

const std::string& RandomDatabaseFixture::user() const
{
    return database_.user();
}

const std::string& RandomDatabaseFixture::password() const
{
    return database_.password();
}

const std::string& RandomDatabaseFixture::connectionString() const
{
    return connectionString_;
}

pgpool3::Pool RandomDatabaseFixture::createPool()
{
    auto constants = pgpool3::PoolConstants(
        MASTER_SIZE, MASTER_MAX_SIZE, SLAVE_SIZE, SLAVE_MAX_SIZE);
    constants.getTimeoutMs = GET_TIMEOUT_MS;
    constants.pingIntervalMs = PING_INTERVAL_MS;
    constants.timeoutEarlyOnMasterUnavailable = false;

    return pgpool3::Pool(
        database_.connectionString(),
        std::move(constants));
}

/*****************************************************************************/
/*                    M A P S P R O   D B   F I X T U R E                    */
/*****************************************************************************/
MapsproDbFixture::MapsproDbFixture()
{
    database_.runPgMigrate(DEFAULT_MAPSPRO_DB_MIGRATIONS_PATH);
}


} // unittest
} // wiki
} // maps
