#include "feed_for_ui.h"

namespace maps::wiki::socialsrv {

namespace mwsf = social::feedback;

namespace {

social::TIds collectIds(const mwsf::Tasks& tasks)
{
    social::TIds retVal;
    for (const auto& task: tasks) {
        retVal.emplace(task.id());
    }
    return retVal;
}

} // unnamed namespace

TaskFeedForUI makeFeedForUI(
    social::feedback::GatewayRO& gatewayRo,
    social::feedback::TaskFeed&& feed,
    serialize::SubstitutionStrategy substitutionStrategy,
    std::optional<uint64_t> totalCount)
{
    serialize::TasksForUI tasks;
    auto taskIds = collectIds(feed.tasks);
    REQUIRE(taskIds.size() == feed.tasks.size(),
        "no task duplicates accepted");  // because we want to move history below
    auto taskIdToHistory = gatewayRo.history(taskIds);
    for (auto& task : feed.tasks) {
        mwsf::History history = [&]() {
            auto historyIt = taskIdToHistory.find(task.id());
            if (historyIt != taskIdToHistory.end()) {
                return std::move(historyIt->second);
            }
            return mwsf::History{};
        }();
        tasks.emplace_back(
            std::move(task),
            std::move(history),
            substitutionStrategy,
            social::Comments{},
            mwsf::TaskOperations{},
            0);
    }
    return TaskFeedForUI{std::move(tasks), feed.hasMore, totalCount};
}

} // maps::wiki::socialsrv
