from typing import List, Optional
from sqlmodel import Session, select
from app.core.base_repository import BaseRepository
from app.models.AnnuityInsuranceModel import AnnuityInsuranceModel
from app.schemas.AnnuityInsuranceSchema import AnnuityInsuranceCreate, AnnuityInsuranceUpdate
from app.utils.transaction_generator import generate_transaction_number

class AnnuityInsuranceRepository(BaseRepository[AnnuityInsuranceModel, AnnuityInsuranceCreate, AnnuityInsuranceUpdate]):
    def __init__(self, session: Session):
        super().__init__(AnnuityInsuranceModel, session)

    def create(self, obj_in: AnnuityInsuranceCreate) -> AnnuityInsuranceModel:
        obj_data = obj_in.model_dump()
        obj_data['transaction_no'] = generate_transaction_number('annuity')
        
        # Encrypt sensitive fields
        obj_data = self._encrypt_fields(obj_data)
        
        db_obj = self.model(**obj_data)
        return super().create_db_object(db_obj)

    def update(self, db_obj: AnnuityInsuranceModel, obj_in: AnnuityInsuranceUpdate) -> AnnuityInsuranceModel:
        return super().update(db_obj, obj_in)

    def get(self, id: int) -> Optional[AnnuityInsuranceModel]:
        return super().get(id)

    def get_multi(self, skip: int = 0, limit: int = 100) -> List[AnnuityInsuranceModel]:
        return super().get_multi(skip=skip, limit=limit)

    def search_by_name(self, first_name: str = None, last_name: str = None) -> List[AnnuityInsuranceModel]:
        stmt = select(self.model)
        if first_name:
            stmt = stmt.where(self.model.first_name.ilike(f"%{first_name}%"))
        if last_name:
            stmt = stmt.where(self.model.last_name.ilike(f"%{last_name}%"))
        return self.session.exec(stmt).all()

    def search_by_email(self, email: str) -> List[AnnuityInsuranceModel]:
        return self.search_by_field("email", email)

    def get_by_status(self, status: str) -> List[AnnuityInsuranceModel]:
        stmt = select(self.model).where(self.model.quote_status == status)
        return self.session.exec(stmt).all()

    def get_by_investment_range(self, min_amount: float, max_amount: float) -> List[AnnuityInsuranceModel]:
        stmt = select(self.model).where(
            self.model.initial_investment >= min_amount,
            self.model.initial_investment <= max_amount
        )
        return self.session.exec(stmt).all()

    def get_by_payment_frequency(self, frequency: str) -> List[AnnuityInsuranceModel]:
        stmt = select(self.model).where(self.model.payment_frequency == frequency)
        return self.session.exec(stmt).all()

    def get_by_purchase_type(self, purchase_type: str) -> List[AnnuityInsuranceModel]:
        stmt = select(self.model).where(self.model.purchase_type == purchase_type)
        return self.session.exec(stmt).all()