use std::{io::Result, sync::Arc};

use semver::Version;
use tokio::sync::RwLock;

/// ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/database/manager#VersionedDatabase
#[derive(Clone)]
pub struct VersionedDatabase {
    pub inner: Arc<RwLock<Box<dyn crate::rpcchainvm::database::Database + Send + Sync>>>,
    pub version: Version,
}

impl VersionedDatabase {
    pub fn new(
        db: Box<dyn crate::rpcchainvm::database::Database + Send + Sync>,
        version: Version,
    ) -> Self {
        Self {
            inner: Arc::new(RwLock::new(db)),
            version,
        }
    }
}

#[tonic::async_trait]
impl crate::rpcchainvm::database::VersionedDatabase for VersionedDatabase {
    async fn close(&self) -> Result<()> {
        let db = self.inner.read().await;
        match db.close().await {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }
}
