"""
POS Configuration Service - Business Logic Layer
"""

from typing import List, Optional
from uuid import UUID
import structlog

from app.repositories.pos_config_repository import POSConfigurationRepository
from app.schemas.pos_config import POSConfigurationResponse
from app.core.database import get_db_transaction

logger = structlog.get_logger()


class POSConfigurationService:
    """Service layer for POS configuration operations"""

    def __init__(self):
        pass

    async def get_configurations_by_tenant(
        self,
        tenant_id: UUID,
        pos_system: Optional[str] = None,
        is_active: Optional[bool] = None,
        skip: int = 0,
        limit: int = 100
    ) -> List[POSConfigurationResponse]:
        """Get POS configurations for a tenant with filtering"""
        try:
            async with get_db_transaction() as db:
                repository = POSConfigurationRepository(db)
                
                configurations = await repository.get_configurations_by_tenant(
                    tenant_id=tenant_id,
                    pos_system=pos_system,
                    is_active=is_active,
                    skip=skip,
                    limit=limit
                )
                
                # Convert to response schemas using from_orm
                responses = []
                for config in configurations:
                    response = POSConfigurationResponse.from_orm(config)
                    responses.append(response)
                
                return responses
                
        except Exception as e:
            logger.error("Failed to get configurations by tenant", error=str(e), tenant_id=tenant_id)
            raise

    async def count_configurations_by_tenant(
        self,
        tenant_id: UUID,
        pos_system: Optional[str] = None,
        is_active: Optional[bool] = None
    ) -> int:
        """Count POS configurations for a tenant with filtering"""
        try:
            async with get_db_transaction() as db:
                repository = POSConfigurationRepository(db)
                
                count = await repository.count_configurations_by_tenant(
                    tenant_id=tenant_id,
                    pos_system=pos_system,
                    is_active=is_active
                )
                
                return count
                
        except Exception as e:
            logger.error("Failed to count configurations by tenant", error=str(e), tenant_id=tenant_id)
            raise
