/*
    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>
*/
#![feature(if_let_guard)]
pub mod kv;
pub mod query_syntax;
#[cfg(test)]
pub mod test_shared;

use anyhow::Result;
use jellyobject::{ObjectBuffer, Path, Value};

pub type RowNum = u64;
pub type RowIter = Box<dyn Iterator<Item = Result<(RowNum, Vec<u8>)>>>;

pub trait Database: Send + Sync {
    fn transaction(&self, f: &mut dyn FnMut(&mut dyn Transaction) -> Result<()>) -> Result<()>;
}

pub trait Transaction {
    fn insert(&mut self, entry: ObjectBuffer) -> Result<RowNum>;
    fn remove(&mut self, row: RowNum) -> Result<()>;
    fn update(&mut self, row: RowNum, entry: ObjectBuffer) -> Result<()>;
    fn get(&self, row: RowNum) -> Result<Option<ObjectBuffer>>;
    fn query<'a>(
        &'a mut self,
        query: Query,
    ) -> Result<Box<dyn Iterator<Item = Result<(RowNum, Vec<u8>)>> + 'a>>;
    fn query_single(&mut self, query: Query) -> Result<Option<RowNum>>;
    fn count(&mut self, query: Query) -> Result<u64>;
    fn debug_info(&self) -> Result<String>;
}

#[derive(Debug, Default, Clone, PartialEq)]
pub struct Query<'a> {
    pub filter: Filter<'a>,
    pub sort: Sort,
}

#[derive(Debug, Default, Clone, PartialEq)]
pub enum Sort {
    #[default]
    None,
    Random(u64),
    Value(ValueSort),
    TextSearch(Path, String),
}

#[derive(Debug, Clone, PartialEq)]
pub struct ValueSort {
    pub order: SortOrder,
    pub path: Path,
    pub multi: MultiBehaviour,
    pub offset: Option<Vec<u8>>,
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum MultiBehaviour {
    First,
    ForEach,
    Max,
    Min,
    Count,
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum SortOrder {
    Ascending,
    Descending,
}

#[derive(Debug, Clone, Default, PartialEq)]
pub enum Filter<'a> {
    #[default]
    True,
    All(Vec<Filter<'a>>),
    Any(Vec<Filter<'a>>),
    Match(Path, Value<'a>),
    Has(Path),
}
