// Hello, libmdbx — minimal example
// Textbook section: Volume I, chapter 2, "Installation and first launch", section "Minimal example".
// What it demonstrates: the full cycle open (create) → put → get → del → close;
//   the semantics of the two-argument constructor env_managed(path, operate_parameters),
//   which opens only an existing database (analogous to mode == 0 in the C API mdbx_env_open()).
// Build: g++ -std=c++17 -I<libmdbx-include> -I../common 01-hello.c++ -lmdbx
// Run: ./01-hello
// Expected output:
//   got: hello, libmdbx
//   reopen(mode=0) on existing db: ok
//   reopen(mode=0) on missing db: refused (ENOFILE)
//   ok: value = "hello, libmdbx"; deleted
// 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-01-hello.mdbx";
    // erase leftovers from the previous run
    mdbx::env::remove(path);

    // Creation: the constructor with create_parameters creates the DB if it does not exist.
    mdbx::env_managed env(path, mdbx::env_managed::create_parameters(), mdbx::env::operate_parameters());
    {
      auto txn = env.start_write();
      // main table
      auto table = txn.open_map(nullptr);
      txn.insert(table, mdbx::slice("key"), mdbx::slice("hello, libmdbx"));
      txn.commit();
    }
    {
      auto rtxn = env.start_read();
      auto table = rtxn.open_map(nullptr);
      std::cout << "got: " << rtxn.get(table, mdbx::slice("key")).as_string() << "\n";
    }

    // Opening an existing database: the two-argument constructor does not create a new one.
    env.close();
    {
      mdbx::env_managed existing(path, mdbx::env::operate_parameters());
      std::cout << "reopen(mode=0) on existing db: ok\n";
      auto wtxn = existing.start_write();
      auto table = wtxn.open_map(nullptr);
      wtxn.erase(table, mdbx::slice("key"));
      wtxn.commit();
    }

    // Opening a missing database must fail with an error.
    try {
      mdbx::env_managed missing(path + ".absent", mdbx::env::operate_parameters());
      std::cerr << "FAIL: unexpectedly opened a non-existent database\n";
      return EXIT_FAILURE;
    } catch (const std::exception &ex) {
      // missing-file codes (MDBX_ENOFILE) arrive as std::system_error
      std::cout << "reopen(mode=0) on missing db: refused (" << ex.what() << ")\n";
    }

    std::cout << "ok: value = \"hello, libmdbx\"; deleted\n";
    return EXIT_SUCCESS;
  } catch (const std::exception &ex) {
    std::cerr << "error: " << ex.what() << "\n";
    return EXIT_FAILURE;
  }
}