//! Template context builder for Tera templates

use serde::Serialize;
use serde_json::Value;
use std::collections::HashMap;

/// Builder for constructing Tera template context
pub struct TemplateContextBuilder {
    context: tera::Context,
}

impl TemplateContextBuilder {
    /// Create a new empty context builder
    pub fn new() -> Self {
        Self {
            context: tera::Context::new(),
        }
    }

    /// Add form results to the context
    pub fn with_results(mut self, results: &HashMap<String, Value>) -> Self {
        for (key, value) in results {
            self.context.insert(key, value);
        }
        self
    }

    /// Add form definition metadata
    pub fn with_form(mut self, form: &crate::FormDefinition) -> Self {
        self.context.insert("form_name", &form.name);
        if let Some(desc) = &form.description {
            self.context.insert("form_description", desc);
        }
        self
    }

    /// Add environment variables
    pub fn with_env(mut self) -> Self {
        let mut env_vars = HashMap::new();
        for (key, value) in std::env::vars() {
            env_vars.insert(key, value);
        }
        self.context.insert("env", &env_vars);
        self
    }

    /// Add custom data with any serializable type
    pub fn with_data<T: Serialize>(mut self, key: &str, value: &T) -> Self {
        if let Ok(json_value) = serde_json::to_value(value) {
            self.context.insert(key, &json_value);
        }
        self
    }

    /// Add a timestamp (ISO 8601 format)
    pub fn with_timestamp(mut self) -> Self {
        let now = chrono::Utc::now().to_rfc3339();
        self.context.insert("now", &now);
        self
    }

    /// Build and return the context
    pub fn build(self) -> tera::Context {
        self.context
    }
}

impl Default for TemplateContextBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_context_builder_new() {
        let _context = TemplateContextBuilder::new().build();
        // Context created successfully
    }

    #[test]
    fn test_context_builder_with_data() {
        let _context = TemplateContextBuilder::new()
            .with_data("name", &"test".to_string())
            .build();
        // Context with data created successfully
    }

    #[test]
    fn test_context_builder_with_env() {
        let _context = TemplateContextBuilder::new().with_env().build();
        // Context with env created successfully
    }

    #[test]
    fn test_context_builder_chaining() {
        let mut results = HashMap::new();
        results.insert("username".to_string(), json!("alice"));

        let _context = TemplateContextBuilder::new()
            .with_results(&results)
            .with_env()
            .with_timestamp()
            .build();
        // Chained context created successfully
    }
}
