// Reader parking: park/unpark of a long read transaction
// Textbook section: Volume II, chapter 11, "Multithreading", section "Parking".
// What it demonstrates: parking a read-only transaction (park_reading) — the reader
//   releases its slot, allowing writers and GC to make progress; resumption
//   via unpark_reading. After resumption the reader's snapshot does not change
//   (MVCC): it sees the same state as before parking.
// Build: g++ -std=c++17 -I<libmdbx-include> -I../common 16-parking.c++ -lmdbx -pthread
// Run: ./16-parking
// Expected output:
//   reader before park: v1
//   writer committed v2 while reader parked
//   reader after unpark: v1
//   ok: parked reader released slot, resumed with unchanged snapshot
// 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()) + "/mdbx-16-parking.mdbx";
    mdbx::env::remove(path);
    mdbx::env_managed env = example::env_open(path);

    {
      auto txn = env.start_write();
      auto table = txn.open_map(nullptr);
      txn.insert(table, mdbx::slice("key"), mdbx::slice("v1"));
      txn.commit();
    }

    auto rtxn = env.start_read();
    auto table = rtxn.open_map(nullptr);
    std::cout << "reader before park: " << rtxn.get(table, mdbx::slice("key")).as_string() << "\n";

    // Parking: the reader stops holding the snapshot; the writer can commit.
    rtxn.park_reading(false);
    {
      auto wtxn = env.start_write();
      auto wtable = wtxn.open_map(nullptr);
      wtxn.upsert(wtable, mdbx::slice("key"), mdbx::slice("v2"));
      wtxn.commit();
    }
    std::cout << "writer committed v2 while reader parked\n";

    // Resumption: the reader continues to work with its previous snapshot.
    rtxn.unpark_reading(true);
    std::cout << "reader after unpark: " << rtxn.get(table, mdbx::slice("key")).as_string() << "\n";
    rtxn.abort();

    std::cout << "ok: parked reader released slot, resumed with unchanged snapshot\n";
    return EXIT_SUCCESS;
  } catch (const std::exception &ex) {
    std::cerr << "error: " << ex.what() << "\n";
    return EXIT_FAILURE;
  }
}