#include "last_processed_time.h"

#include <maps/libs/common/include/exception.h>

namespace maps::wiki::tasks_feedback {

namespace {

const std::string TIME = "time_unix_ms";

}

uint64_t lastProcessedTimeMs(
    pqxx::transaction_base& coreTxn,
    const std::string& tableName)
{
    std::string query = "SELECT " + TIME + " FROM " + tableName;

    auto rows = coreTxn.exec(query);
    REQUIRE(rows.size() == 1, tableName + " should contain exactly 1 row");

    return rows.front()[TIME].as<uint64_t>();
}

void setLastProcessedTimeMs(
    uint64_t timeUnixMs,
    pqxx::transaction_base& coreTxn,
    const std::string& tableName)
{
    std::string truncQuery = "TRUNCATE TABLE " + tableName;
    coreTxn.exec(truncQuery);

    std::string insertQuery =
        "INSERT INTO " + tableName + " (" + TIME + ") " +
        "VALUES (" + std::to_string(timeUnixMs) + ")";
    coreTxn.exec(insertQuery);
}

} // namespace maps::wiki::tasks_feedback
