// config-store, slice 05: transactional commands and rollback
// Textbook section: Volume I, chapter 5, "Transactions — first steps", §5.2/§5.4.
// What is added: a grouped operation in one transaction; rollback via abort;
//   read-only transactions see only committed values.
//   Note: a reader and a writer of the same thread cannot overlap
//   (MDBX_TXN_OVERLAPPING); a stable snapshot "on top" of the writer is held by
//   a separate thread — see examples/c++/04-transactions.c++.
// Build: g++ -std=c++17 -I<libmdbx-include> -I../common config-store-05.c++ -lmdbx
// Run: ./config-store-05
// Expected output:
//   after first commit: theme = dark
//   committed batch: host = localhost, port = 8080
//   after rollback of second batch: port still = 8080, debug absent
//   ok: config-store-05 works
// On failure — message to stderr and exit 1.
//
// SPDX-License-Identifier: Apache-2.0

#include <iostream>
#include <string>

#include "common.h++"
#include <mdbx.h++>

int main() {
  try {
    const std::string path = std::string(example::tmpdir()) + "/config-store-05.mdbx";
    mdbx::env::remove(path);
    mdbx::env_managed env = example::env_open(path);

    // A batch of changes committed by one transaction.
    {
      auto txn = env.start_write();
      auto table = txn.open_map(nullptr);
      txn.upsert(table, mdbx::slice("theme"), mdbx::slice("dark"));
      txn.upsert(table, mdbx::slice("host"), mdbx::slice("localhost"));
      txn.upsert(table, mdbx::slice("port"), mdbx::slice("8080"));
      txn.commit();
    }

    {
      auto rtxn = env.start_read();
      auto table = rtxn.open_map(nullptr);
      std::cout << "after first commit: theme = " << rtxn.get(table, mdbx::slice("theme")).as_string() << "\n";
      rtxn.abort();
    }

    // A batch that will be rolled back (abort): the changes are not saved.
    {
      auto txn = env.start_write();
      auto table = txn.open_map(nullptr);
      txn.upsert(table, mdbx::slice("port"), mdbx::slice("9999"));
      txn.upsert(table, mdbx::slice("debug"), mdbx::slice("on"));
      // rollback
      txn.abort();
    }

    {
      auto rtxn = env.start_read();
      auto table = rtxn.open_map(nullptr);
      std::cout << "committed batch: host = " << rtxn.get(table, mdbx::slice("host")).as_string()
                << ", port = " << rtxn.get(table, mdbx::slice("port")).as_string() << "\n";
      std::cout << "after rollback of second batch: port still = " << rtxn.get(table, mdbx::slice("port")).as_string()
                << ", debug absent\n";
      try {
        (void)rtxn.get(table, mdbx::slice("debug"));
        std::cerr << "FAIL: rolled-back key appeared\n";
        return EXIT_FAILURE;
      } catch (const mdbx::not_found &) {
        // expected
      }
      rtxn.abort();
    }

    std::cout << "ok: config-store-05 works\n";
    return EXIT_SUCCESS;
  } catch (const std::exception &ex) {
    std::cerr << "error: " << ex.what() << "\n";
    return EXIT_FAILURE;
  }
}