#include "get_task_by_commit.h"
#include "helpers.h"
#include <maps/wikimap/mapspro/services/editor/src/branch_helpers.h>
#include <maps/wikimap/mapspro/services/editor/src/exception.h>
#include <maps/wikimap/mapspro/services/editor/src/acl_utils.h>
#include <maps/wikimap/mapspro/services/editor/src/social_utils.h>

#include <yandex/maps/wiki/social/gateway.h>

namespace maps {
namespace wiki {

GetSocialModerationTaskByCommit::Request::Request(
        TUid uid,
        TCommitId commitId,
        Token token)
    : user(uid)
    , commitId(commitId)
    , token(std::move(token))
{
    CHECK_REQUEST_PARAM(uid);
    CHECK_REQUEST_PARAM(commitId);
}

std::string
GetSocialModerationTaskByCommit::Request::dump() const
{
    std::stringstream ss;
    ss << " uid: " << user
       << " commit-id: " << commitId
       << " token: " << token;
    return ss.str();
}


GetSocialModerationTaskByCommit::GetSocialModerationTaskByCommit(const Request& request)
    : controller::BaseController<GetSocialModerationTaskByCommit>(BOOST_CURRENT_FUNCTION)
    , request_(request)
{}

std::string
GetSocialModerationTaskByCommit::printRequest() const
{
    return request_.dump();
}

void
GetSocialModerationTaskByCommit::control()
{
    auto branchCtx = CheckedTrunkBranchContextFacade()
        .acquireReadCoreSocial(request_.token);
    auto permissionsChecker = CheckPermissions(
        request_.user, branchCtx.txnCore());

    checkUserActiveStatus(branchCtx, request_.user);
    moderation::checkAclTaskInfo(branchCtx.txnCore(), request_.user);

    social::Gateway socialGw(branchCtx.txnSocial());
    auto tasks = socialGw.loadEditTasksByCommitIds({request_.commitId});
    WIKI_REQUIRE(
        tasks.size() == 1,
        ERR_NOT_FOUND,
        "Not existing moderation task by commit id: " << request_.commitId);
    result_->task = make_unique<social::Task>(std::move(tasks.front()));
    result_->alerts = loadPermittedAlerts(
        result_->task->id(), socialGw, permissionsChecker);
}

} // namespace wiki
} // namespace maps
