// use tokio::sync::{OnceCell, Mutex};
// use redis::{Connection, ConnectionLike, JsonCommands, RedisResult};
// use rocket::serde::{Deserialize, Serialize};


// static DB_POOL: OnceCell<redis::Client> = OnceCell::const_new();
// static DB_CONNECTOR: OnceCell<Mutex<Connection>> = OnceCell::const_new();

// pub async fn get_pool(URI: &str) -> &'static redis::Client {
//     DB_POOL.get_or_init(|| async {
//         redis::Client::open(URI).expect("[ERR] Can't connect to database.")
//     }).await
// }


// // Async‑compatible accessor
// pub async fn get_conn() -> tokio::sync::MutexGuard<'static, Connection> {
//     DB_CONNECTOR
//         .get()
//         .expect("Redis not initialised")
//         .lock()
//         .await
// }


// pub async fn get_data<T>(key: &str, con: &mut Connection) -> RedisResult<(T)>
// where T: Deserialize<'static> {
//     let raw_data: String = con.json_get(&key, ".")?;
//     Ok( serde_json::from_str(&raw_data)? )
// }

// pub async fn set_data<T>(key: &str, data: &T, con: &mut Connection) -> RedisResult<()>
// where T: Serialize,
// {
//     Ok( con.json_set(&key, "$", &data)? )
// }

use tokio::sync::OnceCell;
use tokio::sync::Mutex;
use redis::{Client, Connection};

static DB_POOL: OnceCell<Client> = OnceCell::const_new();
static DB_CONNECTOR: OnceCell<Mutex<Connection>> = OnceCell::const_new();

pub async fn get_pool(uri: &str) -> redis::RedisResult<()> {
    let client = Client::open(uri)?;
    DB_POOL.set(client).ok();

    let conn = DB_POOL
        .get()
        .unwrap()
        .get_connection()
        ?;
    DB_CONNECTOR.set(Mutex::new(conn)).ok();

    Ok(())
}

// Async‑compatible accessor
pub async fn get_conn() -> tokio::sync::MutexGuard<'static, Connection> {
    DB_CONNECTOR
        .get()
        .expect("Redis not initialised")
        .lock()
        .await
}

// TODO TOKIIO AND MUTEX

// async fn test<RV>() -> RedisResult<()> {
//     let _pool = redis::get_pool(constants::DB_URI).await;
//     let mut con = redis::get_conn();

//     let data1 =   SensorData {
//         id: Some(1),
//         city_codename_cords_sector_cell: String::from("CERCELL:[40.7128,-74.0060]::S1:C1"),
//         sensor_name_and_model:  String::from("Humidity:[DHT22]"),
//         value: 20.7,
//         unit: String::from("RH"),
//         timestamp: 17000002
//     };

//     con.son_set::<&str, &str, SensorData, RV>("asd", "$", &data1);
//     Ok(())
// }
