#include "last_deployed_branch.h"

namespace maps::wiki::social::feedback {

namespace {
namespace sql {
namespace table {

const std::string LAST_DEPLOYED_BRANCH = "service.feedback_last_deployed_branch";

} // table

namespace col {

const std::string ID = "id";

} // col
} // sql
} // unnamed namespace

std::optional<TId> lastDeployedBranchId(pqxx::transaction_base& coreTxn)
{
    std::stringstream query;
    query << "SELECT " << sql::col::ID << " "
          << "FROM " << sql::table::LAST_DEPLOYED_BRANCH;
    auto rows = coreTxn.exec(query.str());
    if (!rows.empty()) {
        return rows[0][sql::col::ID].as<TId>();
    }
    return std::nullopt;
}

void setLastDeployedBranchId(pqxx::transaction_base& coreTxn, TId id)
{
    {
        std::stringstream query;
        query << "TRUNCATE TABLE " << sql::table::LAST_DEPLOYED_BRANCH;
        coreTxn.exec(query.str());
    }
    {
        std::stringstream query;
        query << "INSERT INTO " << sql::table::LAST_DEPLOYED_BRANCH << " "
              << "(" << sql::col::ID << ")"
              << "VALUES (" << id << ")";
        coreTxn.exec(query.str());
    }
}

} // namespace maps::wiki::social::feedback
