/*
  Copyright <2018-2025> <scott.e.graves@protonmail.com>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/
#include "data_db.hpp"

#include "utils/error.hpp"
#include "utils/path.hpp"

namespace monitarr {
data_db::~data_db() noexcept { close(); }

void data_db::close() {
  if (db_) {
    db_->Close();
    db_.reset();
  }
}

auto data_db::get(std::string_view download_id) const
    -> std::optional<data_entry> {
  MONITARR_USES_FUNCTION_NAME();

  std::optional<data_entry> ret;
  if (not perform_action(
          function_name,
          [&download_id, &ret](rocksdb::TransactionDB *txn_db) -> auto {
            std::string value;
            auto res = txn_db->Get(rocksdb::ReadOptions{}, download_id, &value);
            if (res.ok()) {
              ret = nlohmann::json::parse(value).get<data_entry>();
            }

            return res.IsNotFound() ? rocksdb::Status{} : res;
          })) {
    utils::error::handle_error(function_name,
                               fmt::format("failed to get|{}", download_id));
  }

  return ret;
}

void data_db::open(std::string_view data_dir, std::string_view log_dir) {
  MONITARR_USES_FUNCTION_NAME();

  auto db_path = utils::path::combine(data_dir, {"state_db"});
  utils::error::handle_info(function_name,
                            fmt::format("opening database|{}", db_path));

  rocksdb::Options options{};
  options.create_if_missing = true;
  options.create_missing_column_families = true;
  options.db_log_dir = utils::path::combine(log_dir, {"state_db"});
  options.keep_log_file_num = 10;

  rocksdb::TransactionDB *ptr{};
  auto status = rocksdb::TransactionDB::Open(
      options, rocksdb::TransactionDBOptions{}, db_path, &ptr);
  if (not status.ok()) {
    throw utils::error::create_exception(function_name,
                                         {
                                             "failed to open database",
                                             db_path,
                                             status.ToString(),
                                         });
  }

  db_ = std::shared_ptr<rocksdb::TransactionDB>(ptr);
}

auto data_db::perform_action(
    std::string_view function_name,
    std::function<rocksdb::Status(rocksdb::TransactionDB *tx_db)> action) const
    -> bool {
  try {
    auto res = action(db_.get());
    if (not res.ok()) {
      utils::error::handle_error(function_name, res.ToString());
    }

    return res.ok();
  } catch (const std::exception &ex) {
    utils::error::handle_exception(function_name, ex);
  }

  return false;
}

auto data_db::perform_action(
    std::string_view function_name,
    std::function<rocksdb::Status(rocksdb::Transaction *txn)> action) -> bool {
  std::unique_ptr<rocksdb::Transaction> txn{
      db_->BeginTransaction(rocksdb::WriteOptions{},
                            rocksdb::TransactionOptions{}),
  };

  try {
    auto res = action(txn.get());
    if (res.ok()) {
      auto commit_res = txn->Commit();
      if (commit_res.ok()) {
        return true;
      }

      utils::error::handle_error(function_name,
                                 "rocksdb commit failed|" + res.ToString());
      return false;
    }

    utils::error::handle_error(function_name,
                               "rocksdb action failed|" + res.ToString());
  } catch (const std::exception &ex) {
    utils::error::handle_exception(function_name, ex);
  }

  auto rollback_res = txn->Rollback();
  utils::error::handle_error(function_name, "rocksdb rollback failed|" +
                                                rollback_res.ToString());
  return false;
}

void data_db::remove(std::string_view download_id) {
  MONITARR_USES_FUNCTION_NAME();

  if (not perform_action(function_name,
                         [&download_id](rocksdb::Transaction *txn) -> auto {
                           return txn->Delete(download_id);
                         })) {
    utils::error::handle_error(function_name,
                               fmt::format("failed to remove|{}", download_id));
  }
}

void data_db::set(const data_entry &entry) {
  MONITARR_USES_FUNCTION_NAME();

  if (not perform_action(
          function_name, [&entry](rocksdb::Transaction *txn) -> auto {
            return txn->Put(entry.download_id, nlohmann::json(entry).dump());
          })) {
    utils::error::handle_error(
        function_name,
        fmt::format("failed to set|{}", nlohmann::json(entry).dump(2)));
  }
}
} // namespace monitarr
