use std::time::Duration;

use neon_rs::sql::client::{self, MySQL, Params};
use sqlx::{MySql, Pool};

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

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

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

    let min_conns = cfg.get_int(&format!("{cfg_key}.options.min_conns")).unwrap_or(10);
    let max_conns = cfg.get_int(&format!("{cfg_key}.options.max_conns")).unwrap_or(20);
    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 = Params {
        min_conns: Some(min_conns as u32),
        max_conns: Some(max_conns 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 = client::open::<MySQL>(dsn, Some(params)).await?;

    Ok(pool)
}
