use std::time::Duration;

use neon_rs::redix::{
    self, PoolParams,
    factory::{Single, SinglePool},
};

use crate::core::config::config;

pub async fn new(cfg_key: &str) -> anyhow::Result<SinglePool> {
    let cfg = config();

    let dsn = cfg.get_string(&format!("{cfg_key}.dsn"))?;

    let max_size = cfg.get_int(&format!("{cfg_key}.options.max_size")).unwrap_or(100);
    let min_idle = cfg.get_int(&format!("{cfg_key}.options.min_idle")).unwrap_or(10);
    let conn_timeout = cfg.get_int(&format!("{cfg_key}.options.conn_timeout")).unwrap_or(10);
    let idle_timeout = cfg.get_int(&format!("{cfg_key}.options.idle_timeout")).unwrap_or(300);
    let max_lifetime = cfg.get_int(&format!("{cfg_key}.options.max_lifetime")).unwrap_or(600);

    let params = PoolParams {
        max_size: Some(max_size as u32),
        min_idle: Some(min_idle as u32),
        conn_timeout: Some(Duration::from_secs(conn_timeout as u64)),
        idle_timeout: Some(Duration::from_secs(idle_timeout as u64)),
        max_lifetime: Some(Duration::from_secs(max_lifetime as u64)),
    };

    let pool = redix::open::<Single>(vec![dsn], Some(params)).await?;

    Ok(pool)
}
