#include "feedback_task_binder.h"

#include <maps/wikimap/mapspro/services/editor/src/objects_cache.h>
#include <maps/wikimap/mapspro/services/editor/src/exception.h>

#include <yandex/maps/wiki/social/feedback/commits.h>
#include <yandex/maps/wiki/social/feedback/gateway_ro.h>
#include <yandex/maps/wiki/social/feedback/task_filter.h>

namespace maps {
namespace wiki {

Observer::ContextDataPtr
FeedbackTaskBinder::beforeCommit(
    ObjectsCache& cache,
    const GeoObjectCollection&,
    UserContext& /*userContext*/,
    const CommitContext& commitContext) const
{
    if (!commitContext.feedbackTaskId) {
        return {};
    }

    const auto& commit = cache.savedCommit();
    auto& branchCtx = cache.branchContext();

    auto tasks = social::feedback::GatewayRO(branchCtx.txnSocial()).tasksByFilter(
        social::feedback::TaskFilter().acquiredBy(commit.createdBy()));

    if (!tasks.empty() && tasks[0].id() == *commitContext.feedbackTaskId) {
        social::feedback::bindCommitsToTask(
                branchCtx.txnSocial(),
                *commitContext.feedbackTaskId,
                {commit.id()});
    } else {
        THROW_WIKI_LOGIC_ERROR(ERR_BAD_DATA,
                "Feedback " << *commitContext.feedbackTaskId
                << " isn't acquired by user " << commit.createdBy());
    }

    return {};
}


} // namespace wiki
} // namespace maps
