#include "get_review.h"
#include "helpers.h"
#include <maps/wikimap/mapspro/services/social/src/api/globals.h>
#include <maps/wikimap/mapspro/services/social/src/libs/yacare/error.h>

namespace maps::wiki::socialsrv {
namespace {
const std::string TASK_NAME = "GetReview";
} // namespace

GetReview::GetReview(
        const Request& request,
        taskutils::TaskID asyncTaskID)
    : controller::BaseController<GetReview>(GetReview::taskName(), asyncTaskID)
    , request_(request)
{ }

std::string GetReview::Request::dump() const
{
    return
        "review-id: " + std::to_string(reviewId) +
        " uid: " + std::to_string(uid);
}

void GetReview::control()
{
    checkPermissionsToWorkWithReviews(request_.uid, ReviewAccessMode::View);
    auto socialReadTxn = Globals::dbPools().socialReadTxn(request_.token);
    const auto review = mwsf::ReviewsGateway(*socialReadTxn)
                    .getReview(request_.reviewId);
    if (review.state() == mwsf::ReviewState::Draft) {
        SOCIAL_REQUIRE(review.createdBy() == request_.uid, Forbidden,
            "Forbidden to view others draft reviews.");
        checkPermissionsToWorkWithReviews(request_.uid, ReviewAccessMode::Edit);
    }
    const auto reviewExternData = getReviewExternData(
        review,
        *Globals::dbPools().coreReadTxn(),
        *socialReadTxn,
        request_.uid == review.createdBy()
            ? IncludeTasksWithoutComments::Yes
            : IncludeTasksWithoutComments::No);
    if (request_.uid != review.createdBy()) {
        checkAccessToReviewContents(reviewExternData, request_.uid);
    }
    result_->resultJson = toJson(review, request_.uid, reviewExternData);
}

const std::string&
GetReview::taskName()
{
    return TASK_NAME;
}

} // namespace maps::wiki::socialsrv
