#include "create_task.h"

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

namespace maps::wiki {

namespace {
const std::string TASK_METHOD_NAME = "CreateSpravTask";
}

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

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

std::string
CreateSpravTask::Request::dump() const
{
    std::stringstream ss;
    ss << " uid: " << user;
    ss << " oid: " << objectId;
    return ss.str();
}

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

void
CreateSpravTask::control()
{
    auto branchCtx = BranchContextFacade().acquireWrite();
    auto user = getUser(branchCtx, request_.user);
    user.checkActiveStatus();
    auto originalTask = OriginalTask::fromJsonString(request_.body);
    std::stringstream queryStream;
    auto& txn = branchCtx.txnSocial();
    queryStream
        << "INSERT INTO " + SPRAV_TASKS_TABLE + " (object_id, permalink, original_task, created_by)"
        << " VALUES(" << request_.objectId << ","
        << originalTask.permalink()
        << ", " << txn.quote(request_.body) << "," << request_.user << ")";
    txn.exec(queryStream.str());
    result_->token = branchCtx.commit();
    result_->taskName = taskName();
}

} // namespace maps::wiki
