/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

pub mod memory;
pub mod redb;
pub mod rocksdb;

use crate::backends::{memory::Memory, redb::Redb, rocksdb::Rocksdb};
use anyhow::{Result, bail};
use std::{path::Path, sync::Arc};

pub type WriteTxnFunction = dyn FnMut(&mut dyn WriteTransaction) -> Result<()>;
pub type ReadTxnFunction = dyn FnMut(&dyn ReadTransaction) -> Result<()>;

pub trait Db {
    fn write_transaction(&self, f: &mut WriteTxnFunction) -> Result<()>;
    fn read_transaction(&self, f: &mut ReadTxnFunction) -> Result<()>;
}
pub trait WriteTransaction: ReadTransaction {
    fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()>;
    fn del(&mut self, key: &[u8]) -> Result<()>;
}
pub trait ReadTransaction {
    fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;
    fn iter<'a>(
        &'a self,
        key: &[u8],
        reverse: bool,
    ) -> Result<Box<dyn Iterator<Item = Result<Vec<u8>>> + 'a>>;
}

pub fn create_backend(driver: &str, path: &Path) -> Result<Arc<dyn Db>> {
    Ok(match driver {
        "rocksdb" => Arc::new(Rocksdb::new(path)?),
        "redb" => Arc::new(Redb::new(path)?),
        "memory" => Arc::new(Memory::new()),
        _ => bail!("unknown db driver"),
    })
}
