from typing import List, Optional
from sqlmodel import Session, select
from app.core.base_repository import BaseRepository
from app.models.RentersInsuranceModel import RentersInsuranceModel
from app.schemas.RentersInsuranceSchema import RentersInsuranceCreate, RentersInsuranceUpdate
from app.utils.transaction_generator import generate_transaction_number
import json

class RentersInsuranceRepository(BaseRepository[RentersInsuranceModel, RentersInsuranceCreate, RentersInsuranceUpdate]):
    def __init__(self, session: Session):
        super().__init__(RentersInsuranceModel, session)

    def create(self, obj_in: RentersInsuranceCreate) -> RentersInsuranceModel:
        obj_data = obj_in.model_dump()
        
        # Generate transaction number
        obj_data['transaction_no'] = generate_transaction_number('renters')
        
        # Convert lists to JSON strings for storage
        if obj_data.get('scheduled_personal_property'):
            obj_data['scheduled_personal_property'] = json.dumps(obj_data['scheduled_personal_property'])
        
        # Encrypt sensitive fields
        obj_data = self._encrypt_fields(obj_data)
        
        db_obj = self.model(**obj_data)
        created_obj = super().create_db_object(db_obj)
        
        # Convert JSON fields back to lists for response
        self._convert_json_fields_to_lists(created_obj)
        return created_obj

    def update(self, db_obj: RentersInsuranceModel, obj_in: RentersInsuranceUpdate) -> RentersInsuranceModel:
        obj_data = obj_in.model_dump(exclude_unset=True)
        
        # Convert lists to JSON strings for storage
        if 'scheduled_personal_property' in obj_data and obj_data['scheduled_personal_property']:
            obj_data['scheduled_personal_property'] = json.dumps(obj_data['scheduled_personal_property'])
        
        updated_obj = super().update(db_obj, obj_in)
        
        # Convert JSON fields back to lists for response
        self._convert_json_fields_to_lists(updated_obj)
        return updated_obj

    def get(self, id: int) -> Optional[RentersInsuranceModel]:
        db_obj = super().get(id)
        if db_obj:
            self._convert_json_fields_to_lists(db_obj)
        return db_obj

    def get_multi(self, skip: int = 0, limit: int = 100) -> List[RentersInsuranceModel]:
        db_objs = super().get_multi(skip=skip, limit=limit)
        for db_obj in db_objs:
            self._convert_json_fields_to_lists(db_obj)
        return db_objs

    def _convert_json_fields_to_lists(self, db_obj: RentersInsuranceModel):
        """Convert JSON string fields back to Python lists"""
        json_fields = ['scheduled_personal_property']
        
        for field in json_fields:
            field_value = getattr(db_obj, field, None)
            if field_value and isinstance(field_value, str):
                try:
                    setattr(db_obj, field, json.loads(field_value))
                except (json.JSONDecodeError, TypeError):
                    setattr(db_obj, field, [])

    def search_by_name(self, name: str) -> List[RentersInsuranceModel]:
        # Search by first name or last name
        stmt = select(self.model).where(
            (self.model.first_name.ilike(f"%{name}%")) |
            (self.model.last_name.ilike(f"%{name}%"))
        )
        results = self.session.exec(stmt).all()
        for result in results:
            self._convert_json_fields_to_lists(result)
        return results

    def search_by_email(self, email: str) -> List[RentersInsuranceModel]:
        results = self.search_by_field("email_address", email)
        for result in results:
            self._convert_json_fields_to_lists(result)
        return results

    def get_by_status(self, status: str) -> List[RentersInsuranceModel]:
        stmt = select(self.model).where(self.model.quote_status == status)
        results = self.session.exec(stmt).all()
        for result in results:
            self._convert_json_fields_to_lists(result)
        return results

    def get_by_property_type(self, property_type: str) -> List[RentersInsuranceModel]:
        stmt = select(self.model).where(self.model.property_type == property_type)
        results = self.session.exec(stmt).all()
        for result in results:
            self._convert_json_fields_to_lists(result)
        return results

    def get_by_coverage_amount_range(self, min_amount: float, max_amount: float) -> List[RentersInsuranceModel]:
        stmt = select(self.model).where(
            self.model.personal_property_coverage >= min_amount,
            self.model.personal_property_coverage <= max_amount
        )
        results = self.session.exec(stmt).all()
        for result in results:
            self._convert_json_fields_to_lists(result)
        return results

    def get_by_state(self, state: str) -> List[RentersInsuranceModel]:
        stmt = select(self.model).where(self.model.state == state)
        results = self.session.exec(stmt).all()
        for result in results:
            self._convert_json_fields_to_lists(result)
        return results