use std::{convert::Infallible, path::PathBuf};

use apexbase::storage::DurabilityLevel;

use crate::{CreatePoolError, Manager, Pool, PoolBuilder, PoolConfig, Runtime};

/// Configuration object for `deadpool-apexbase`.
///
/// # Example (from environment)
///
/// By enabling the `serde` feature you can read the configuration using the
/// [`config`](https://crates.io/crates/config) crate as following:
/// ```env
/// APEXBASE__PATH=/tmp/apex_db
/// APEXBASE__POOL__MAX_SIZE=16
/// APEXBASE__POOL__TIMEOUTS__WAIT__SECS=5
/// APEXBASE__POOL__TIMEOUTS__WAIT__NANOS=0
/// ```
/// ```rust,ignore
/// #[derive(serde::Deserialize, serde::Serialize)]
/// struct Config {
///     apexbase: deadpool_apexbase::Config,
/// }
/// impl Config {
///     pub fn from_env() -> Result<Self, config::ConfigError> {
///         let mut cfg = config::Config::builder()
///            .add_source(config::Environment::default().separator("__"))
///            .build()?;
///            cfg.try_deserialize()
///     }
/// }
/// ```
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Config {
    /// Path to the ApexBase database directory.
    pub path: PathBuf,

    /// Durability level for the database.
    ///
    /// Default: [`DurabilityLevel::Safe`]
    #[cfg_attr(feature = "serde", serde(skip))]
    pub durability: DurabilityLevel,

    /// Whether to drop existing `.apex` files when opening.
    ///
    /// Default: `false`
    #[cfg_attr(feature = "serde", serde(default))]
    pub drop_if_exists: bool,

    /// [`Pool`] configuration.
    #[cfg_attr(feature = "serde", serde(default))]
    pub pool: Option<PoolConfig>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            path: PathBuf::from("apexbase.db"),
            durability: DurabilityLevel::Safe,
            drop_if_exists: false,
            pool: None,
        }
    }
}

impl Config {
    /// Create a new [`Config`] with the given `path` of the database directory.
    #[must_use]
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self {
            path: path.into(),
            durability: DurabilityLevel::Safe,
            drop_if_exists: false,
            pool: None,
        }
    }

    /// Creates a new [`Pool`] using this [`Config`].
    ///
    /// # Errors
    ///
    /// See [`CreatePoolError`] for details.
    pub fn create_pool(&self, runtime: Runtime) -> Result<Pool, CreatePoolError> {
        self.builder(runtime)
            .map_err(CreatePoolError::Config)?
            .build()
            .map_err(CreatePoolError::Build)
    }

    /// Creates a new [`PoolBuilder`] using this [`Config`].
    ///
    /// # Errors
    ///
    /// See [`ConfigError`] for details.
    pub fn builder(&self, runtime: Runtime) -> Result<PoolBuilder, ConfigError> {
        let manager = Manager::from_config(self, runtime);
        Ok(Pool::builder(manager)
            .config(self.get_pool_config())
            .runtime(runtime))
    }

    /// Returns [`deadpool::managed::PoolConfig`] which can be used to construct
    /// a [`deadpool::managed::Pool`] instance.
    #[must_use]
    pub fn get_pool_config(&self) -> PoolConfig {
        self.pool.unwrap_or_default()
    }
}

/// This error is returned if there is something wrong with the ApexBase configuration.
///
/// This is just a type alias to [`Infallible`] at the moment as there
/// is no validation happening at the configuration phase.
pub type ConfigError = Infallible;
