from typing import List, Optional
from sqlmodel.ext.asyncio.session import AsyncSession
from app.cruds import user as crud
from app.schemas.user import UserCreate, UserUpdate
from app.models.user import User

class UserService:
    async def get(self, session: AsyncSession, id: int) -> Optional[User]:
        return await crud.get(session, id)

    async def get_multi(self, session: AsyncSession, skip: int = 0, limit: int = 100) -> List[User]:
        return await crud.get_multi(session, skip=skip, limit=limit)

    async def create(self, session: AsyncSession, obj_in: UserCreate) -> User:
        from app.core.security import get_password_hash
        user_data = obj_in.dict()
        if 'password' in user_data:
            password = user_data.pop('password')
            user_data['hashed_password'] = get_password_hash(password)
        db_obj = User(**user_data)
        session.add(db_obj)
        await session.commit()
        await session.refresh(db_obj)
        return db_obj

    async def update(self, session: AsyncSession, db_obj: User, obj_in: UserUpdate) -> User:
        if hasattr(obj_in, 'password') and obj_in.password:
            from app.core.security import get_password_hash
            db_obj.hashed_password = get_password_hash(obj_in.password)
        
        return await crud.update(session, db_obj, obj_in)

    async def delete(self, session: AsyncSession, id: int) -> User:
        return await crud.delete(session, id)

service = UserService()
