use std::fmt;

use crate::types::Value;

/// A query: its text, an id, and the values of its `{name:Type}`
/// parameters.
#[derive(Clone)]
pub struct Query {
    sql: String,
    id: String,
    params: Vec<(String, Value)>,
}

impl Query {
    pub fn new(sql: impl AsRef<str>) -> Self {
        Self {
            sql: sql.as_ref().to_string(),
            id: "".to_string(),
            params: Vec::new(),
        }
    }

    pub fn id(self, id: impl AsRef<str>) -> Self {
        Self {
            id: id.as_ref().to_string(),
            ..self
        }
    }

    /// Binds `value` to the `{name:Type}` placeholders of the query, which
    /// the server fills in: the value is sent as the text the server parses
    /// for `Type`, never spliced into the SQL. Binding a name again replaces
    /// its value. A parameter of a `Nullable` type that is not bound is NULL.
    ///
    /// ```rust,no_run
    /// # use clickhouse_native_rs::{types::Query, Pool};
    /// # async fn run(pool: Pool) -> Result<(), clickhouse_native_rs::errors::Error> {
    /// let mut client = pool.get_handle().await?;
    /// let query = Query::new("SELECT name FROM users WHERE id = {id:UInt32} AND city = {city:String}")
    ///     .param("id", 42_u32)
    ///     .param("city", "O'Fallon");
    /// let block = client.query(query).fetch_all().await?;
    /// # Ok(()) }
    /// ```
    pub fn param(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
        let name = name.into();
        let value = value.into();
        match self.params.iter_mut().find(|(bound, _)| *bound == name) {
            Some((_, bound)) => *bound = value,
            None => self.params.push((name, value)),
        }
        self
    }

    pub(crate) fn get_sql(&self) -> &str {
        &self.sql
    }

    pub(crate) fn get_id(&self) -> &str {
        &self.id
    }

    pub(crate) fn get_params(&self) -> &[(String, Value)] {
        &self.params
    }

    pub(crate) fn map_sql<F>(self, f: F) -> Self
    where
        F: Fn(&str) -> String,
    {
        Self {
            sql: f(&self.sql),
            ..self
        }
    }
}

/// The names of the parameters, not their values, which may be secrets.
impl fmt::Debug for Query {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let names: Vec<&str> = self.params.iter().map(|(name, _)| name.as_str()).collect();
        f.debug_struct("Query")
            .field("sql", &self.sql)
            .field("id", &self.id)
            .field("params", &names)
            .finish()
    }
}

impl<T> From<T> for Query
where
    T: AsRef<str>,
{
    fn from(source: T) -> Self {
        Self::new(source)
    }
}