from typing import List, Optional
from sqlmodel import Session, select
from datetime import datetime, timezone
from app.models.CommercialPropertyModel import CommercialPropertyModel
from app.schemas.CommercialPropertySchema import CommercialPropertyCreate, CommercialPropertyUpdate
from app.utils.transaction_generator import generate_transaction_number

class CommercialPropertyRepository:
    def __init__(self, session: Session):
        self.session = session

    def create(self, commercial_property_data: CommercialPropertyCreate) -> CommercialPropertyModel:
        """Create a new commercial property quote"""
        obj_data = commercial_property_data.model_dump()
        obj_data['transaction_no'] = generate_transaction_number('commercial_property')
        
        from app.core.security import current_user_var
        user = current_user_var.get()
        if user:
            obj_data['user_id'] = user.get("user_id")
            
        db_commercial_property = CommercialPropertyModel(**obj_data)
        db_commercial_property.encrypt_sensitive_data()
        self.session.add(db_commercial_property)
        self.session.commit()
        self.session.refresh(db_commercial_property)
        db_commercial_property.decrypt_sensitive_data()
        return db_commercial_property

    def get_by_id(self, quote_id: int) -> Optional[CommercialPropertyModel]:
        """Get commercial property quote by ID"""
        quote = self.session.get(CommercialPropertyModel, quote_id)
        if quote:
            quote.decrypt_sensitive_data()
        return quote

    def get_all(self, skip: int = 0, limit: int = 100) -> List[CommercialPropertyModel]:
        """Get all commercial property quotes with pagination and customer filtration"""
        from app.core.security import current_user_var
        user = current_user_var.get()
        
        statement = select(CommercialPropertyModel)
        if user and user.get("role") == "customer":
            statement = statement.where(CommercialPropertyModel.user_id == user["user_id"])
        elif user and user.get("role") == "admin":
            pass
        else:
            statement = statement.where(CommercialPropertyModel.user_id == -1)
            
        statement = statement.offset(skip).limit(limit)
        quotes = self.session.exec(statement).all()
        for quote in quotes:
            quote.decrypt_sensitive_data()
        return quotes

    def update(self, quote_id: int, update_data: CommercialPropertyUpdate) -> Optional[CommercialPropertyModel]:
        """Update commercial property quote"""
        db_commercial_property = self.session.get(CommercialPropertyModel, quote_id)
        if not db_commercial_property:
            return None
        
        update_dict = update_data.model_dump(exclude_unset=True)
        if update_dict:
            update_dict["updated_at"] = datetime.now(timezone.utc)
            for field, value in update_dict.items():
                setattr(db_commercial_property, field, value)
            
            db_commercial_property.encrypt_sensitive_data()
            self.session.add(db_commercial_property)
            self.session.commit()
            self.session.refresh(db_commercial_property)
            db_commercial_property.decrypt_sensitive_data()
        
        return db_commercial_property

    def delete(self, quote_id: int) -> bool:
        """Delete commercial property quote"""
        db_commercial_property = self.session.get(CommercialPropertyModel, quote_id)
        if not db_commercial_property:
            return False
        
        self.session.delete(db_commercial_property)
        self.session.commit()
        return True

    def count(self) -> int:
        """Get total count of commercial property quotes"""
        statement = select(CommercialPropertyModel)
        return len(self.session.exec(statement).all())

    def search(self, query: str, skip: int = 0, limit: int = 100) -> List[CommercialPropertyModel]:
        """Search commercial property quotes by business name, contact name, or email"""
        statement = select(CommercialPropertyModel).where(
            (CommercialPropertyModel.business_name.ilike(f"%{query}%")) |
            (CommercialPropertyModel.contact_name.ilike(f"%{query}%")) |
            (CommercialPropertyModel.email_address.ilike(f"%{query}%"))
        ).offset(skip).limit(limit)
        quotes = self.session.exec(statement).all()
        for quote in quotes:
            quote.decrypt_sensitive_data()
        return quotes

    def get_by_business_name(self, business_name: str) -> List[CommercialPropertyModel]:
        """Get commercial property quotes by business name"""
        statement = select(CommercialPropertyModel).where(
            CommercialPropertyModel.business_name.ilike(f"%{business_name}%")
        )
        quotes = self.session.exec(statement).all()
        for quote in quotes:
            quote.decrypt_sensitive_data()
        return quotes

    def get_by_email(self, email: str) -> List[CommercialPropertyModel]:
        """Get commercial property quotes by email address"""
        statement = select(CommercialPropertyModel).where(
            CommercialPropertyModel.email_address == email
        )
        quotes = self.session.exec(statement).all()
        for quote in quotes:
            quote.decrypt_sensitive_data()
        return quotes

    def get_by_status(self, status: str) -> List[CommercialPropertyModel]:
        """Get commercial property quotes by status"""
        statement = select(CommercialPropertyModel).where(
            CommercialPropertyModel.quote_status == status
        )
        quotes = self.session.exec(statement).all()
        for quote in quotes:
            quote.decrypt_sensitive_data()
        return quotes