# src/infrastructure/adapters/sqlserver/sql_user_repository.py
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from src.domain.ports import UserRepositoryPort
from src.infrastructure.persistence.models import UserModel
from src.domain.entities.user import User as UserEntity
from src.infrastructure.adapters.sqlserver.mappers.mappers import user_model_to_entity, user_entity_to_model

class SqlUserRepository(UserRepositoryPort):
    def __init__(self, session: AsyncSession):
        self._session = session

    async def get_by_email(self, email: str) -> UserEntity | None:
        result = await self._session.execute(
            select(UserModel).where(UserModel.email == email)
        )
        model = result.scalar_one_or_none()
        return user_model_to_entity(model) if model else None

    async def create_user(self, user: UserEntity) -> UserEntity:
        model = user_entity_to_model(user)
        self._session.add(model)
        await self._session.commit()
        await self._session.refresh(model)
        return user_model_to_entity(model)