#include <yandex/maps/wiki/social/feedback/task.h>

#include <maps/wikimap/mapspro/libs/social/feedback/util.h>
#include <maps/wikimap/mapspro/libs/social/helpers.h>
#include <maps/wikimap/mapspro/libs/social/magic_strings.h>

#include <maps/libs/json/include/value.h>
#include <yandex/maps/wiki/social/feedback/attribute_names.h>
#include <yandex/maps/wiki/social/feedback/description_serialize.h>
#include <yandex/maps/wiki/social/feedback/task_patch.h>
#include <yandex/maps/wiki/social/feedback/consts.h>
#include <yandex/maps/wiki/social/gateway.h>

namespace maps::wiki::social::feedback {

Task::Task(const pqxx::row& row, const std::string& tablePrefix) :

    TaskBrief(row, tablePrefix),

    description_(fromJson<Description>(json::Value::fromString(
        rowField(row, sql::col::DESCRIPTION, tablePrefix).as<std::string>()))),

    attrs_(json::Value::fromString(rowField(row, sql::col::ATTRS, tablePrefix).as<std::string>()))
{
}

const Attrs& Task::attrs() const
{
    return attrs_;
}

const Description& Task::description() const
{
    return description_;
}

std::optional<std::string> Task::subSource() const
{
    if (attrs_.existCustom(attrs::SUBSOURCE)) {
        return attrs_.getCustom(attrs::SUBSOURCE);
    } else {
        return std::nullopt;
    }
}

social::Comments loadRelativeComments(
    pqxx::transaction_base& txn,
    const HistoryItems& historyEvents)
{
    social::TIds commentIds;
    for (const auto& event : historyEvents) {
        if (event.commentId()) {
            commentIds.insert(event.commentId().value());
        }
    }

    social::Gateway socialGtw(txn);
    return socialGtw.loadComments(commentIds);
}

} // namespace maps::wiki::social::feedback
