/*
  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.
*/
#ifndef LIBMONITARR_INCLUDE_DATA_DB_HPP_
#define LIBMONITARR_INCLUDE_DATA_DB_HPP_

#include "utils/config.hpp"

namespace monitarr {
struct data_entry final {
  std::string download_id;
  std::uint64_t last_check{};
  std::uint64_t size_left{};
};

class data_db final {
public:
  data_db() noexcept = default;
  data_db(const data_db &) noexcept = default;
  data_db(data_db &&) noexcept = default;

  auto operator=(const data_db &) noexcept -> data_db & = default;
  auto operator=(data_db &&) noexcept -> data_db & = default;

  ~data_db() noexcept;

private:
  std::shared_ptr<rocksdb::TransactionDB> db_;

private:
  [[nodiscard]] auto
  perform_action(std::string_view function_name,
                 std::function<rocksdb::Status(rocksdb::TransactionDB *tx_db)>
                     action) const -> bool;

  [[nodiscard]] auto perform_action(
      std::string_view function_name,
      std::function<rocksdb::Status(rocksdb::Transaction *txn)> action) -> bool;

public:
  void close();

  [[nodiscard]] auto get(std::string_view download_id) const
      -> std::optional<data_entry>;

  void open(std::string_view data_dir, std::string_view log_dir);

  void remove(std::string_view download_id);

  void set(const data_entry &entry);
};
} // namespace monitarr

NLOHMANN_JSON_NAMESPACE_BEGIN template <>
struct adl_serializer<monitarr::data_entry> {
  static void to_json(json &data, const monitarr::data_entry &value) {
    data["download_id"] = value.download_id;
    data["last_check"] = value.last_check;
    data["size_left"] = value.size_left;
  }

  static void from_json(const json &data, monitarr::data_entry &value) {
    data.at("download_id").get_to(value.download_id);
    data.at("last_check").get_to(value.last_check);
    data.at("size_left").get_to(value.size_left);
  }
};
NLOHMANN_JSON_NAMESPACE_END

#endif // LIBMONITARR_INCLUDE_DATA_DB_HPP_
