///|
#external
priv type FsUnitResult

///|
extern "js" fn FsUnitResult::is_ok(self : FsUnitResult) -> Bool =
  #| (res) => res.ok

///|
extern "js" fn FsUnitResult::error_message(self : FsUnitResult) -> String =
  #| (res) => res.content

///|
#module("node:fs")
#borrow(content)
extern "js" fn append_file_sync(path : String, content : Bytes) -> Unit = "appendFileSync"

///|
#borrow(content)
extern "js" fn append_file_ffi(
  append_file : (String, Bytes) -> Unit,
  path : String,
  content : Bytes,
) -> FsUnitResult =
  #| function(appendFile, path, content) {
  #|   try {
  #|     appendFile(path, Buffer.from(content));
  #|     return { ok: true, content: "" };
  #|   } catch (error) {
  #|     return { ok: false, content: error.message };
  #|   }
  #| }

///|
/// Appends a Bytes payload to the file at path for JS target.
pub fn append_bytes_to_file(
  path : String,
  content : Bytes,
) -> Unit raise MoonKVError {
  let res = append_file_ffi(append_file_sync, path, content)
  if !res.is_ok() {
    raise MoonKVError::IOError(
      "Failed to append bytes to file \{path}: " + res.error_message(),
    )
  }
}