use rustler::{Resource, ResourceArc};
use sparrowdb::GraphDb;

rustler::init!("Elixir.SparrowDB");

struct GraphDbResource(GraphDb);

#[rustler::resource_impl]
impl Resource for GraphDbResource {}

#[rustler::nif]
fn open(base: &str) -> Result<ResourceArc<GraphDbResource>, String> {
  match GraphDb::open(std::path::Path::new(base)) {
    Ok(graph) => Ok(ResourceArc::new(GraphDbResource(graph))),
    Err(e) => Err(e.to_string()),
  }
}

#[rustler::nif]
fn query(graph_resource: ResourceArc<GraphDbResource>, cypher: &str) -> Result<String, String> {
  let db = &graph_resource.0;
  match db.execute(cypher) {
    Ok(response) => Ok(format!("{:?}", response)),
    Err(e) => Err(e.to_string()),
  }
}
