use roboticus_core::error::{Result, RoboticusError};

/// Extension trait for converting any Display error into RoboticusError::Database.
pub trait DbResultExt<T> {
    fn db_err(self) -> Result<T>;
}

impl<T, E: std::fmt::Display> DbResultExt<T> for std::result::Result<T, E> {
    fn db_err(self) -> Result<T> {
        self.map_err(|e| RoboticusError::Database(e.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn db_result_ext_converts_error() {
        let err: std::result::Result<(), &str> = Err("test error");
        let converted = err.db_err();
        assert!(converted.is_err());
        match converted.unwrap_err() {
            RoboticusError::Database(msg) => assert_eq!(msg, "test error"),
            other => panic!("Expected Database, got {:?}", other),
        }
    }
}
