import logging
from typing import Optional, Dict, Any, List

from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession

from models.presales_messages import Presales_messages

logger = logging.getLogger(__name__)


# ------------------ Service Layer ------------------
class Presales_messagesService:
    """Service layer for Presales_messages operations"""

    def __init__(self, db: AsyncSession):
        self.db = db

    async def create(self, data: Dict[str, Any]) -> Optional[Presales_messages]:
        """Create a new presales_messages"""
        try:
            obj = Presales_messages(**data)
            self.db.add(obj)
            await self.db.commit()
            await self.db.refresh(obj)
            logger.info(f"Created presales_messages with id: {obj.id}")
            return obj
        except Exception as e:
            await self.db.rollback()
            logger.error(f"Error creating presales_messages: {str(e)}")
            raise

    async def get_by_id(self, obj_id: int) -> Optional[Presales_messages]:
        """Get presales_messages by ID"""
        try:
            query = select(Presales_messages).where(Presales_messages.id == obj_id)
            result = await self.db.execute(query)
            return result.scalar_one_or_none()
        except Exception as e:
            logger.error(f"Error fetching presales_messages {obj_id}: {str(e)}")
            raise

    async def get_list(
        self, 
        skip: int = 0, 
        limit: int = 20, 
        query_dict: Optional[Dict[str, Any]] = None,
        sort: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Get paginated list of presales_messagess"""
        try:
            query = select(Presales_messages)
            count_query = select(func.count(Presales_messages.id))
            
            if query_dict:
                for field, value in query_dict.items():
                    if hasattr(Presales_messages, field):
                        query = query.where(getattr(Presales_messages, field) == value)
                        count_query = count_query.where(getattr(Presales_messages, field) == value)
            
            count_result = await self.db.execute(count_query)
            total = count_result.scalar()

            if sort:
                if sort.startswith('-'):
                    field_name = sort[1:]
                    if hasattr(Presales_messages, field_name):
                        query = query.order_by(getattr(Presales_messages, field_name).desc())
                else:
                    if hasattr(Presales_messages, sort):
                        query = query.order_by(getattr(Presales_messages, sort))
            else:
                query = query.order_by(Presales_messages.id.desc())

            result = await self.db.execute(query.offset(skip).limit(limit))
            items = result.scalars().all()

            return {
                "items": items,
                "total": total,
                "skip": skip,
                "limit": limit,
            }
        except Exception as e:
            logger.error(f"Error fetching presales_messages list: {str(e)}")
            raise

    async def update(self, obj_id: int, update_data: Dict[str, Any]) -> Optional[Presales_messages]:
        """Update presales_messages"""
        try:
            obj = await self.get_by_id(obj_id)
            if not obj:
                logger.warning(f"Presales_messages {obj_id} not found for update")
                return None
            for key, value in update_data.items():
                if hasattr(obj, key):
                    setattr(obj, key, value)

            await self.db.commit()
            await self.db.refresh(obj)
            logger.info(f"Updated presales_messages {obj_id}")
            return obj
        except Exception as e:
            await self.db.rollback()
            logger.error(f"Error updating presales_messages {obj_id}: {str(e)}")
            raise

    async def delete(self, obj_id: int) -> bool:
        """Delete presales_messages"""
        try:
            obj = await self.get_by_id(obj_id)
            if not obj:
                logger.warning(f"Presales_messages {obj_id} not found for deletion")
                return False
            await self.db.delete(obj)
            await self.db.commit()
            logger.info(f"Deleted presales_messages {obj_id}")
            return True
        except Exception as e:
            await self.db.rollback()
            logger.error(f"Error deleting presales_messages {obj_id}: {str(e)}")
            raise

    async def get_by_field(self, field_name: str, field_value: Any) -> Optional[Presales_messages]:
        """Get presales_messages by any field"""
        try:
            if not hasattr(Presales_messages, field_name):
                raise ValueError(f"Field {field_name} does not exist on Presales_messages")
            result = await self.db.execute(
                select(Presales_messages).where(getattr(Presales_messages, field_name) == field_value)
            )
            return result.scalar_one_or_none()
        except Exception as e:
            logger.error(f"Error fetching presales_messages by {field_name}: {str(e)}")
            raise

    async def list_by_field(
        self, field_name: str, field_value: Any, skip: int = 0, limit: int = 20
    ) -> List[Presales_messages]:
        """Get list of presales_messagess filtered by field"""
        try:
            if not hasattr(Presales_messages, field_name):
                raise ValueError(f"Field {field_name} does not exist on Presales_messages")
            result = await self.db.execute(
                select(Presales_messages)
                .where(getattr(Presales_messages, field_name) == field_value)
                .offset(skip)
                .limit(limit)
                .order_by(Presales_messages.id.desc())
            )
            return result.scalars().all()
        except Exception as e:
            logger.error(f"Error fetching presales_messagess by {field_name}: {str(e)}")
            raise