#include "load.h"
#include <maps/wikimap/mapspro/libs/assessment/impl/magic_strings.h>

#include <maps/wikimap/mapspro/libs/common/include/yandex/maps/wiki/common/pg_utils.h>

namespace maps::wiki::assessment::competences {

std::optional<TId> get(pqxx::transaction_base& txn, const std::string& roleName)
{
    const auto result = txn.exec(
        "SELECT " +
            sql::col::COMPETENCE_ID + " "
        "FROM " +
            sql::table::COMPETENCE + " "
        "WHERE " +
            sql::col::ROLE_NAME + " = " + txn.quote(roleName) + " "
        "LIMIT 2");

    REQUIRE(
        result.size() <= 1,
        result.size() << " competences selected by role " << roleName);

    if (result.empty()) {
        return {};
    }
    return result[0][sql::col::COMPETENCE_ID].as<TId>();
}

namespace {

Competence makeCompetence(const pqxx::row& row)
{
    return {
        .id = row[sql::col::COMPETENCE_ID].as<TId>(),
        .roleName = row[sql::col::ROLE_NAME].as<std::string>()
    };
}

} // namespace

CompetenceVec load(pqxx::transaction_base& txn, const std::vector<std::string>& roleNames)
{
    const auto result = txn.exec(
        "SELECT " +
            sql::col::COMPETENCE_ID + ", " +
            sql::col::ROLE_NAME + " "
        "FROM " +
            sql::table::COMPETENCE + " "
        "WHERE " +
            sql::col::ROLE_NAME + " " + common::sqlInCondition(roleNames));

    CompetenceVec competences;
    competences.reserve(result.size());

    for (const auto& row : result) {
        competences.emplace_back(makeCompetence(row));
    }
    return competences;
}

} // maps::wiki::assessment::competences
