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

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

from models.contact_inquiries import Contact_inquiries

logger = logging.getLogger(__name__)


# ------------------ Service Layer ------------------
class Contact_inquiriesService:
    """Service layer for Contact_inquiries operations"""

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

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

    async def get_by_id(self, obj_id: int) -> Optional[Contact_inquiries]:
        """Get contact_inquiries by ID"""
        try:
            query = select(Contact_inquiries).where(Contact_inquiries.id == obj_id)
            result = await self.db.execute(query)
            return result.scalar_one_or_none()
        except Exception as e:
            logger.error(f"Error fetching contact_inquiries {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 contact_inquiriess"""
        try:
            query = select(Contact_inquiries)
            count_query = select(func.count(Contact_inquiries.id))
            
            if query_dict:
                for field, value in query_dict.items():
                    if hasattr(Contact_inquiries, field):
                        query = query.where(getattr(Contact_inquiries, field) == value)
                        count_query = count_query.where(getattr(Contact_inquiries, 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(Contact_inquiries, field_name):
                        query = query.order_by(getattr(Contact_inquiries, field_name).desc())
                else:
                    if hasattr(Contact_inquiries, sort):
                        query = query.order_by(getattr(Contact_inquiries, sort))
            else:
                query = query.order_by(Contact_inquiries.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 contact_inquiries list: {str(e)}")
            raise

    async def update(self, obj_id: int, update_data: Dict[str, Any]) -> Optional[Contact_inquiries]:
        """Update contact_inquiries"""
        try:
            obj = await self.get_by_id(obj_id)
            if not obj:
                logger.warning(f"Contact_inquiries {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 contact_inquiries {obj_id}")
            return obj
        except Exception as e:
            await self.db.rollback()
            logger.error(f"Error updating contact_inquiries {obj_id}: {str(e)}")
            raise

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

    async def get_by_field(self, field_name: str, field_value: Any) -> Optional[Contact_inquiries]:
        """Get contact_inquiries by any field"""
        try:
            if not hasattr(Contact_inquiries, field_name):
                raise ValueError(f"Field {field_name} does not exist on Contact_inquiries")
            result = await self.db.execute(
                select(Contact_inquiries).where(getattr(Contact_inquiries, field_name) == field_value)
            )
            return result.scalar_one_or_none()
        except Exception as e:
            logger.error(f"Error fetching contact_inquiries 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[Contact_inquiries]:
        """Get list of contact_inquiriess filtered by field"""
        try:
            if not hasattr(Contact_inquiries, field_name):
                raise ValueError(f"Field {field_name} does not exist on Contact_inquiries")
            result = await self.db.execute(
                select(Contact_inquiries)
                .where(getattr(Contact_inquiries, field_name) == field_value)
                .offset(skip)
                .limit(limit)
                .order_by(Contact_inquiries.id.desc())
            )
            return result.scalars().all()
        except Exception as e:
            logger.error(f"Error fetching contact_inquiriess by {field_name}: {str(e)}")
            raise