// Error handling: parsing return codes, retry strategy
// Textbook section: Volume II, chapter 12, "Error handling",
//   sections "Codes", "Retry strategies".
// What it demonstrates: handling of expected codes (MDBX_KEYEXIST, MDBX_NOTFOUND)
//   as exceptions mdbx::key_exists/mdbx::not_found; reading the numeric code from
//   the exception; a retry pattern on MDBX_BUSY (environment busy).
// Build: g++ -std=c++17 -I<libmdbx-include> -I../common 17-error-handling.c++ -lmdbx
// Run: ./17-error-handling
// Expected output:
//   key_exists: code=<N> (MDBX_KEYEXIST: Key/data pair already exists)
//   not_found: code=<N> (MDBX_NOTFOUND: No matching key/data pair found)
//   busy attempt 1: failed (<reason>)
//   busy: persists after 3 attempts (expected while env is open)
//   ok: expected codes parsed, retry pattern shown
// On failure — message to stderr and exit 1.
//
// SPDX-License-Identifier: Apache-2.0

#include <iostream>
#include <string>

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

namespace {

// Prints the code and the name of the exception.
void report(const char *label, const mdbx::exception &ex) {
  std::cout << label << ": code=" << ex.error().code() << " (" << ex.what() << ")\n";
}

} // namespace

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

    auto txn = env.start_write();
    auto table = txn.open_map(nullptr);

    // MDBX_KEYEXIST — the expected code when inserting an existing key.
    txn.insert(table, mdbx::slice("key"), mdbx::slice("v1"));
    try {
      txn.insert(table, mdbx::slice("key"), mdbx::slice("v2"));
      std::cerr << "FAIL: duplicate insert did not throw\n";
      return EXIT_FAILURE;
    } catch (const mdbx::key_exists &ex) {
      report("key_exists", ex);
    }

    // MDBX_NOTFOUND — the expected code when reading a missing key.
    try {
      (void)txn.get(table, mdbx::slice("absent"));
      std::cerr << "FAIL: get of absent key did not throw\n";
      return EXIT_FAILURE;
    } catch (const mdbx::not_found &ex) {
      report("not_found", ex);
    }
    txn.commit();

    // Retry strategy: an attempt to open the environment exclusively while
    // it is already open by the current process yields "busy" (MDBX_BUSY on
    // process contention, or the system error EAGAIN within a single process).
    // Such a failure is caught and handled by retrying with a limit.
    const int max_attempts = 3;
    int attempt = 0;
    for (; attempt < max_attempts; ++attempt) {
      try {
        mdbx::env_managed busy(path, mdbx::env::operate_parameters().exclusive());
        std::cerr << "FAIL: exclusive open unexpectedly succeeded\n";
        return EXIT_FAILURE;
      } catch (const std::exception &ex) {
        std::cout << "busy attempt " << (attempt + 1) << ": failed (" << ex.what() << ")\n";
      }
    }
    std::cout << "busy: persists after " << attempt << " attempts (expected while env is open)\n";

    std::cout << "ok: expected codes parsed, retry pattern shown\n";
    return EXIT_SUCCESS;
  } catch (const std::exception &ex) {
    std::cerr << "error: " << ex.what() << "\n";
    return EXIT_FAILURE;
  }
}