//! {{MainType}} service handler
//!
//! Contains business logic for {{MainType}} operations.

use crate::types::{{MainType}};
use crate::{{{ToolName}}Error, {{ToolName}}ErrorKind, Result};
use std::collections::HashMap;

/// Service for managing {{MainType}} instances
#[derive(Debug, Clone)]
pub struct {{MainType}}Service {
    items: std::sync::Arc<tokio::sync::Mutex<HashMap<String, {{MainType}}>>>,
}

impl {{MainType}}Service {
    /// Create a new service instance
    pub fn new() -> Self {
        Self {
            items: std::sync::Arc::new(tokio::sync::Mutex::new(HashMap::new())),
        }
    }

    /// Create a new {{MainType}}
    pub async fn create(&self, name: impl Into<String>, description: impl Into<String>) -> Result<{{MainType}}> {
        let item = {{MainType}}::new(name, description);
        let mut items = self.items.lock().await;
        items.insert(item.id.clone(), item.clone());
        Ok(item)
    }

    /// Get a {{MainType}} by ID
    pub async fn get(&self, id: &str) -> Result<{{MainType}}> {
        let items = self.items.lock().await;
        items.get(id)
            .cloned()
            .ok_or_else(|| {{ToolName}}Error::new(
                {{ToolName}}ErrorKind::ValidationError(format!("{{MainType}} not found: {}", id)),
                "get {{MainType}}",
            ))
    }

    /// List all {{MainType}} instances
    pub async fn list(&self) -> Result<Vec<{{MainType}}>> {
        let items = self.items.lock().await;
        Ok(items.values().cloned().collect())
    }

    /// Update a {{MainType}}
    pub async fn update(&self, id: &str, name: impl Into<String>, description: impl Into<String>) -> Result<{{MainType}}> {
        let mut items = self.items.lock().await;
        let mut item = items.get_mut(id)
            .ok_or_else(|| {{ToolName}}Error::new(
                {{ToolName}}ErrorKind::ValidationError(format!("{{MainType}} not found: {}", id)),
                "update {{MainType}}",
            ))?
            .clone();

        item.set_name(name);
        item.set_description(description);
        items.insert(id.to_string(), item.clone());
        Ok(item)
    }

    /// Delete a {{MainType}}
    pub async fn delete(&self, id: &str) -> Result<()> {
        let mut items = self.items.lock().await;
        items.remove(id)
            .ok_or_else(|| {{ToolName}}Error::new(
                {{ToolName}}ErrorKind::ValidationError(format!("{{MainType}} not found: {}", id)),
                "delete {{MainType}}",
            ))?;
        Ok(())
    }
}

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

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

    #[tokio::test]
    async fn test_create() {
        let service = {{MainType}}Service::new();
        let item = service.create("Test", "Description").await.expect("should create");
        assert_eq!(item.name, "Test");
    }

    #[tokio::test]
    async fn test_get() {
        let service = {{MainType}}Service::new();
        let created = service.create("Test", "Description").await.expect("should create");
        let retrieved = service.get(&created.id).await.expect("should get");
        assert_eq!(created.id, retrieved.id);
    }

    #[tokio::test]
    async fn test_list() {
        let service = {{MainType}}Service::new();
        service.create("Item1", "Desc1").await.expect("should create");
        service.create("Item2", "Desc2").await.expect("should create");
        let items = service.list().await.expect("should list");
        assert_eq!(items.len(), 2);
    }

    #[tokio::test]
    async fn test_update() {
        let service = {{MainType}}Service::new();
        let item = service.create("Test", "Description").await.expect("should create");
        let updated = service.update(&item.id, "Updated", "New Description").await.expect("should update");
        assert_eq!(updated.name, "Updated");
    }

    #[tokio::test]
    async fn test_delete() {
        let service = {{MainType}}Service::new();
        let item = service.create("Test", "Description").await.expect("should create");
        service.delete(&item.id).await.expect("should delete");
        let result = service.get(&item.id).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_not_found() {
        let service = {{MainType}}Service::new();
        let result = service.get("nonexistent").await;
        assert!(result.is_err());
    }
}
