#include "complete.h"

#include "acquire.h"

#include <maps/wikimap/mapspro/libs/assessment/impl/magic_strings.h>
#include <maps/wikimap/mapspro/libs/assessment/impl/sql_helpers.h>

namespace maps::wiki::assessment::samples {

void tryCompleteTask(
    pqxx::transaction_base& txn,
    TId unitId,
    TUid acquiredBy,
    TId gradeId)
{
    const auto result = txn.exec(
        "UPDATE " + sql::table::SAMPLE_TASK + " "
        "SET " +
            sql::col::GRADE_ID + " = " + std::to_string(gradeId) + " "
        "WHERE " +
            sql::col::GRADE_ID + " IS NULL AND " +
            sql::col::UNIT_ID + " = " + std::to_string(unitId) + " AND " +
            sql::col::ACQUIRED_BY + " = " + std::to_string(acquiredBy) + " AND " +
            sql::col::ACQUIRED_AT + " > NOW() - " + ACQUISITION_TIMEOUT_INTERVAL + " "
        "RETURNING " +
            sql::col::SAMPLE_TASK_ID);

    /* Query is expected to update 2 rows at most, as
         1. Tasks from samples of the same qualification can not have the same unitId
         2. User can acquire from each sample onlу a single task at a time */
    REQUIRE(
        result.affected_rows() <= 2,
        "Attempt to complete sample task "
        "by unit " << unitId << " and user " << acquiredBy << " "
        "affects " << result.affected_rows() << " tasks");
}

} // maps::wiki::assessment::samples
