#include "clear.h"
#include "logging.h"

#include <maps/wikimap/mapspro/services/editor/src/branch_helpers.h>
#include <maps/wikimap/mapspro/services/editor/src/check_permissions.h>

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

namespace maps {
namespace wiki {

namespace {

const std::string TASK_METHOD_NAME = "ClearUserComments";

} // namespace

ClearUserComments::Request::Request(UserContext userContext, TUid createdBy)
    : userContext(std::move(userContext))
    , createdBy(createdBy)
{
    CHECK_REQUEST_PARAM(createdBy);
}

std::string
ClearUserComments::Request::dump() const
{
    std::stringstream ss;
    ss << "uid: " << userId()
       << "created by: " << createdBy;
    return ss.str();
}


ClearUserComments::ClearUserComments(
        const ObserverCollection&,
        const Request& request,
        taskutils::TaskID asyncTaskID)
    : controller::BaseController<ClearUserComments>(BOOST_CURRENT_FUNCTION, asyncTaskID)
    , request_(request)
{}

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

void
ClearUserComments::control()
{
    auto branchCtx = CheckedTrunkBranchContextFacade().acquireWrite();

    const auto& user = request_.userContext.aclUser(branchCtx);
    user.checkActiveStatus();

    CheckPermissions(request_.userId(), branchCtx.txnCore()).checkPermissionsForGroupDeleteComments();

    social::Gateway socialGateway(branchCtx.txnSocial());

    auto comments = socialGateway.clearUserComments(request_.createdBy, request_.userId());

    if (!comments.empty()) {
        request_.userContext.saveActivity(
            branchCtx, social::UserActivityAction::ClearComments, std::nullopt);
    }

    for (const auto& comment : comments) {
        logDeleteComment(comment);
    }
    result_->count = comments.size();
    result_->token = branchCtx.commit();
}

const std::string&
ClearUserComments::taskName()
{
    return TASK_METHOD_NAME;
}

} // namespace wiki
} // namespace maps
