/**
 *
 * Agora Real Time Engagement
 * Created by Wei Hu in 2022-09.
 * Copyright (c) 2022 Agora IO. All rights reserved.
 *
 */
#pragma once

#include "rte_config.h"

#include <node_api.h>

#include "lib/signature.h"
#include "rte_runtime/sanitizer/thread_check.h"
#include "schema/value.h"

#define RTE_NODEJS_VALUE_SIGNATURE 0x0AB57914CAA175C4U

/**
 * @brief For the coding and architecture consistency of the overall RTE nodejs
 * binding, the architecture of the JS value also uses the so-called
 * 'shared-ptr' architecture, and the shared-ptr is used to destroy the value
 * bridge. However, only JS value holds the reference count of the shared-ptr,
 * and C value does _not_ hold the reference count of the shared-ptr, that is
 * to say, the JS value has full control over the life cycle of not only the JS
 * value, but also the value bridge, and the underlying C value, in other words,
 * as long as the JS value is finalized, it will destroy the value bridge, and
 * the underlying C value.
 */
typedef struct rte_nodejs_value_t {
  rte_signature_t signature;

  // Used to determine the timing of destroying this value bridge. See above
  // comments for important notice about the usage of this shared_ptr.
  rte_sharedptr_t* shared_ptr;

  rte_value_t* c_value;  // Point to the corresponding C value.
  napi_ref js_ref;       // Point to the corresponding JS value.

  rte_sanitizer_thread_check_t thread_check;
} rte_nodejs_value_t;

AGORA_RTE_PRIVATE_API bool rte_nodejs_value_check_integrity(
    rte_nodejs_value_t* self, bool check_thread);

AGORA_RTE_API napi_value rte_nodejs_value_module_init(napi_env env,
                                                      napi_value exports);

AGORA_RTE_PRIVATE_API napi_value rte_nodejs_value_wrap(napi_env env,
                                                       rte_value_t* value);
