#include <maps/wikimap/mapspro/libs/taskutils/impl/reader.h>

#include <maps/wikimap/mapspro/libs/taskutils/impl/taskmanager_impl.h>
#include <maps/wikimap/mapspro/libs/taskutils/include/token.h>

namespace maps::wiki::taskutils {

TaskResult
Reader::load(Transaction& work, const Token& token) const
{
    if (token.expired()) {
        return TaskManagerImpl::createTaskResult(TaskStatus::Expired);
    }

    return load(work, token.id());
}

TaskResult
Reader::load(Transaction& work, TaskID id) const
{
    auto query =
        "SELECT status, result, error_message, expires <= NOW() AS is_expired"
        " FROM " + dbSchema_ + ".taskutils_tasks"
        " WHERE id=" + std::to_string(id);

    auto r = work.exec(query);
    if (r.empty()) {
        return TaskResult();
    }

    const auto& row = r[0];
    if (row[3].as<bool>()) {
        return TaskManagerImpl::createTaskResult(TaskStatus::Expired);
    }

    return TaskManagerImpl::createTaskResult(
        row[0].as<std::string>(),
        row[1].as<std::string>(),
        row[2].as<std::string>());
}

} // namespace maps::wiki::taskutils
