use reqwest::blocking::Client;

const BASE_URL: &str = "http://localhost:8123";
const USER: &str = "default";
const PASSWORD: &str = "clickhouse";

pub struct ClickhouseClient {
    client: Client,
}

impl ClickhouseClient {
    pub fn new() -> Self {
        Self {
            client: Client::new(),
        }
    }

    pub fn execute(&self, sql: &str) -> Result<String, String> {
        let url = format!("{}?user={}&password={}", BASE_URL, USER, PASSWORD);
        let response = self
            .client
            .post(&url)
            .body(sql.to_string())
            .send()
            .map_err(|e| format!("Request failed: {}", e))?;

        if response.status().is_success() {
            response
                .text()
                .map_err(|e| format!("Failed to read response: {}", e))
        } else {
            let status = response.status();
            let body = response.text().unwrap_or_default();
            Err(format!("HTTP {}: {}", status, body))
        }
    }

    pub fn is_available(&self) -> bool {
        let url = format!("{}/ping", BASE_URL);
        self.client
            .get(&url)
            .send()
            .map(|response| response.status().is_success())
            .unwrap_or(false)
    }

    pub fn query(&self, sql: &str) -> Result<String, String> {
        self.execute(sql)
    }
}

mod dml;
mod sql_validation;
mod table_ddl;
