#pragma once

#include <aotffi/callback.h>

#include <memory>
#include <span>

#include "array.h"
#include "call_platform.h"

namespace ctypes {

using AotClosureHandler = aotffi::CallbackHandler;
using AotSlotHandle = aotffi::SlotHandle;

struct AotCallbackState {
  aotffi::SlotHandle closure;
  aotffi::CallbackSignature sig_;

  AotCallbackState() = default;
  AotCallbackState(const AotCallbackState&) = delete;
  AotCallbackState& operator=(const AotCallbackState&) = delete;
  AotCallbackState(AotCallbackState&&) = delete;
  AotCallbackState& operator=(AotCallbackState&&) = delete;

  [[nodiscard]] bool PrepareCIF(Napi::Env env, CType result, std::span<const TypeSpec> args, CallConv conv);
  [[nodiscard]] bool AllocateClosure(void*& code_ptr);
  [[nodiscard]] bool PrepareClosure(AotClosureHandler handler,
                                    void* context,
                                    void* code_ptr,
                                    std::shared_ptr<void> strong_owner = {},
                                    std::weak_ptr<void> weak_owner = {});
};

void AotCallbackHandler(void* ret, void** args, void* user_data);
void AotThreadSafeCallbackHandler(void* ret, void** args, void* user_data);

}  // namespace ctypes
