use std::sync::Arc;
use teloxide::dispatching::dialogue::{RedisStorage, serializer::Json, ErasedStorage};
use teloxide::dispatching::dialogue::Storage;
use color_eyre::Result;

pub async fn create_redis_storage<S>(redis_url_env: &str) -> Result<Arc<ErasedStorage<S>>> 
where
    S: Send + Sync + serde::Serialize + for<'de> serde::Deserialize<'de> + 'static,
{
    let redis_url = std::env::var(redis_url_env);

    if redis_url.is_err() {
        log::error!("Redis URL {} not found in environment variables", redis_url_env);
        return Err(color_eyre::eyre::eyre!("Redis URL {} not found in environment variables", redis_url_env));
    }
    
    let storage = RedisStorage::open(&redis_url.unwrap(), Json)
        .await
        .map_err(|e| color_eyre::eyre::eyre!("Failed to create Redis storage for {}: {}", redis_url_env, e))?;
    
    log::info!("Redis storage created successfully for {} with JSON serialization", redis_url_env);
    Ok(storage.erase())
}