from typing import List, Optional
from sqlmodel import Session, select
from datetime import datetime, timezone
from app.models.GroupHealthModel import GroupHealthModel
from app.schemas.GroupHealthSchema import GroupHealthCreate, GroupHealthUpdate
from app.utils.transaction_generator import generate_transaction_number

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

    def create(self, group_health_data: GroupHealthCreate) -> GroupHealthModel:
        """Create a new group health quote"""
        obj_data = group_health_data.model_dump()
        obj_data['transaction_no'] = generate_transaction_number('group_health')
        
        from app.core.security import current_user_var
        user = current_user_var.get()
        if user:
            obj_data['user_id'] = user.get("user_id")
            
        db_group_health = GroupHealthModel(**obj_data)
        db_group_health.encrypt_sensitive_data()
        self.session.add(db_group_health)
        self.session.commit()
        self.session.refresh(db_group_health)
        db_group_health.decrypt_sensitive_data()
        return db_group_health

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

    def get_all(self, skip: int = 0, limit: int = 100) -> List[GroupHealthModel]:
        """Get all group health quotes with pagination and customer filtration"""
        from app.core.security import current_user_var
        user = current_user_var.get()
        
        statement = select(GroupHealthModel)
        if user and user.get("role") == "customer":
            statement = statement.where(GroupHealthModel.user_id == user["user_id"])
        elif user and user.get("role") == "admin":
            pass
        else:
            statement = statement.where(GroupHealthModel.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 get_by_company_name(self, company_name: str) -> List[GroupHealthModel]:
        """Get group health quotes by company name"""
        statement = select(GroupHealthModel).where(
            GroupHealthModel.company_name.ilike(f"%{company_name}%")
        )
        return self.session.exec(statement).all()

    def get_by_email(self, email: str) -> List[GroupHealthModel]:
        """Get group health quotes by contact email"""
        statement = select(GroupHealthModel).where(
            GroupHealthModel.contact_email == email
        )
        return self.session.exec(statement).all()

    def get_by_status(self, status: str) -> List[GroupHealthModel]:
        """Get group health quotes by status"""
        statement = select(GroupHealthModel).where(
            GroupHealthModel.quote_status == status
        )
        return self.session.exec(statement).all()

    def update(self, quote_id: int, update_data: GroupHealthUpdate) -> Optional[GroupHealthModel]:
        """Update group health quote"""
        db_group_health = self.session.get(GroupHealthModel, quote_id)
        if not db_group_health:
            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_group_health, field, value)
            
            db_group_health.encrypt_sensitive_data()
            self.session.add(db_group_health)
            self.session.commit()
            self.session.refresh(db_group_health)
            db_group_health.decrypt_sensitive_data()
        
        return db_group_health

    def delete(self, quote_id: int) -> bool:
        """Delete group health quote"""
        db_group_health = self.session.get(GroupHealthModel, quote_id)
        if not db_group_health:
            return False
        
        self.session.delete(db_group_health)
        self.session.commit()
        return True

    def count(self) -> int:
        """Get total count of group health quotes"""
        statement = select(GroupHealthModel)
        return len(self.session.exec(statement).all())

    def search(self, query: str, skip: int = 0, limit: int = 100) -> List[GroupHealthModel]:
        """Search group health quotes by company name, contact name, or email"""
        statement = select(GroupHealthModel).where(
            (GroupHealthModel.company_name.ilike(f"%{query}%")) |
            (GroupHealthModel.contact_person_name.ilike(f"%{query}%")) |
            (GroupHealthModel.contact_email.ilike(f"%{query}%"))
        ).offset(skip).limit(limit)
        return self.session.exec(statement).all()