from sqlalchemy import func
from sqlalchemy.orm import joinedload

from core.config import get_db
from core.security.authentication import hash_password, get_user
from core.security.exceptions import CoreDBError
from models import Parent, Payment
from schema.parent import ParentResponseSchema


class ParentService:

    def create(self,request):
        with get_db() as db:
            payload = request.model_dump(exclude=['password', 'confirm_password'])
            payload['hashed_password'] =hashed_password = hash_password(request.confirm_password)
            payload['sur_name']=request.last_name
            try:
                new_user = Parent(**payload)
                db.add(new_user)
                db.commit()
                db.refresh(new_user)
            except Exception as e:
                db.rollback()
                raise CoreDBError(f"Could not create account: {e}")

    def update_profile(self,parent_id,request):
        with get_db() as db:
            payload=request.model_dump()
            print(payload)
            try:
                db.query(Parent).filter(Parent.id==parent_id).update(payload)
                db.commit()
            except Exception as e:
                db.rollback()
                raise CoreDBError(f"Could not create account: {e}")


    def get_parent_profile(self,parent_id):
        with get_db() as db:
            instance=db.query(Parent).filter(Parent.id==parent_id).first()
            data= ParentResponseSchema.model_validate(instance).model_dump()

            used_wallet_sum = (
                db.query(func.sum(Payment.used_wallet_amount))
                .filter(
                    Payment.user_type == 'parent',
                    Payment.created_by == parent_id
                )
                .scalar()
            )

            # Handle None case (if no records found)
            used_wallet_sum = used_wallet_sum or 0
            data['used_wallet_amount'] = used_wallet_sum

            return data

    def fetch_all_parents(self):
        with get_db() as db:
            records=db.query(Parent).options(joinedload(Parent.participants)).filter(Parent.deleted_at.is_(None)).all()
            print(records)
            return [ParentResponseSchema.model_validate(record).model_dump() for record in records]

