Documentation
use crate::document::document::BaseDocument;
use mongodb::options::{ClientOptions, CreateIndexOptions};
use mongodb::{Client, Collection, Database, IndexModel};
use std::error::Error;

/// Get a database client by providing a database connection string
pub async fn db_client(client_uri: String) -> Result<Client, Box<dyn Error>> {
    let options = ClientOptions::parse(&client_uri).await?;

    let client = Client::with_options(options)?;
    Ok(client)
}

/// Get a database instance by providing a database connection string and the database name
pub async fn init_db(client_uri: String, database_name: &str) -> Result<Database, Box<dyn Error>> {
    let client = db_client(client_uri)
        .await
        .expect("could not connect to database");

    let database = client.database(database_name);
    Ok(database)
}

/// Utility function to create indexes by providing the collection, the indexes to be created and whatever index options you need.
pub async fn create_indexes<T: BaseDocument>(
    collection: Collection<T>,
    indexes: Vec<IndexModel>,
    options: Option<CreateIndexOptions>,
) {
    match collection.create_indexes(indexes, options).await {
        Ok(index) => println!("{:?}", index.index_names),
        Err(e) => println!("{:?}", e),
    }
}