"""Business logic services for {{ module_name_title }} microservice module."""

import logging
from datetime import datetime
from typing import List, Optional
from sqlalchemy.orm import Session

from .models import {{ module_name_title }}
from .schemas import {{ module_name_title }}Create, {{ module_name_title }}Update

logger = logging.getLogger(__name__)


class {{ module_name_title }}Service:
    """Service class for {{ module_name_title }} operations in microservice architecture."""
    
    def __init__(self, db: Session):
        self.db = db
    
    def create_{{ module_name }}(self, {{ module_name }}_data: {{ module_name_title }}Create) -> {{ module_name_title }}:
        """Create a new {{ module_name_title }}."""
        try:
            db_{{ module_name }} = {{ module_name_title }}(
                name={{ module_name }}_data.name,
                description={{ module_name }}_data.description
            )
            
            self.db.add(db_{{ module_name }})
            self.db.commit()
            self.db.refresh(db_{{ module_name }})
            
            logger.info(f"Created {{ module_name_title }} with ID: {db_{{ module_name }}.id}")
            return db_{{ module_name }}
            
        except Exception as e:
            logger.error(f"Error creating {{ module_name_title }}: {str(e)}")
            raise
    
    def get_{{ module_name }}(self, {{ module_name }}_id: int) -> Optional[{{ module_name_title }}]:
        """Get a {{ module_name_title }} by ID."""
        return self.db.query({{ module_name_title }}).filter({{ module_name_title }}.id == {{ module_name }}_id).first()
    
    def get_{{ module_name_plural }}(self, skip: int = 0, limit: int = 100) -> List[{{ module_name_title }}]:
        """Get {{ module_name_plural }} with pagination."""
        return self.db.query({{ module_name_title }}).offset(skip).limit(limit).all()
    
    def update_{{ module_name }}(self, {{ module_name }}_id: int, {{ module_name }}_data: {{ module_name_title }}Update) -> Optional[{{ module_name_title }}]:
        """Update an existing {{ module_name_title }}."""
        try:
            db_{{ module_name }} = self.get_{{ module_name }}({{ module_name }}_id)
            if not db_{{ module_name }}:
                return None
            
            # Update fields
            update_data = {{ module_name }}_data.dict(exclude_unset=True)
            for field, value in update_data.items():
                setattr(db_{{ module_name }}, field, value)
            
            db_{{ module_name }}.updated_at = datetime.utcnow()
            
            self.db.commit()
            self.db.refresh(db_{{ module_name }})
            
            logger.info(f"Updated {{ module_name_title }} with ID: {db_{{ module_name }}.id}")
            return db_{{ module_name }}
            
        except Exception as e:
            logger.error(f"Error updating {{ module_name_title }} { {{ module_name }}_id}: {str(e)}")
            raise
    
    def delete_{{ module_name }}(self, {{ module_name }}_id: int) -> bool:
        """Delete a {{ module_name_title }}."""
        try:
            db_{{ module_name }} = self.get_{{ module_name }}({{ module_name }}_id)
            if not db_{{ module_name }}:
                return False
            
            self.db.delete(db_{{ module_name }})
            self.db.commit()
            
            logger.info(f"Deleted {{ module_name_title }} with ID: { {{ module_name }}_id}")
            return True
            
        except Exception as e:
            logger.error(f"Error deleting {{ module_name_title }} { {{ module_name }}_id}: {str(e)}")
            raise
    
    def get_{{ module_name_plural }}_count(self) -> int:
        """Get total count of {{ module_name_plural }}."""
        return self.db.query({{ module_name_title }}).count()
    
    def search_{{ module_name_plural }}(self, search_term: str, skip: int = 0, limit: int = 100) -> List[{{ module_name_title }}]:
        """Search {{ module_name_plural }} by name or description."""
        search_pattern = f"%{search_term}%"
        return self.db.query({{ module_name_title }}).filter(
            ({{ module_name_title }}.name.ilike(search_pattern)) |
            ({{ module_name_title }}.description.ilike(search_pattern))
        ).offset(skip).limit(limit).all()


class HealthService:
    """Service for health checks and monitoring."""
    
    def __init__(self, db: Session):
        self.db = db
    
    def check_database_health(self) -> bool:
        """Check if database connection is healthy."""
        try:
            # Simple query to test database connection
            self.db.execute("SELECT 1")
            return True
        except Exception as e:
            logger.error(f"Database health check failed: {str(e)}")
            return False
    
    def get_service_stats(self) -> dict:
        """Get basic service statistics."""
        try:
            total_{{ module_name_plural }} = self.db.query({{ module_name_title }}).count()
            
            return {
                "total_{{ module_name_plural }}": total_{{ module_name_plural }},
                "database_healthy": self.check_database_health(),
                "timestamp": datetime.utcnow()
            }
        except Exception as e:
            logger.error(f"Error getting service stats: {str(e)}")
            return {
                "error": str(e),
                "timestamp": datetime.utcnow()
            }
