from sqlalchemy import select

{% if has_redis %}
from {{ name }}.db.sql.models.user import User
from {{ name }}.db.sql.utils.session import s
{% else %}
from {{ name }}.db.models.user import User
from {{ name }}.db.utils.session import s
{% endif %}


async def create_or_update_user(
    telegram_id: int,
    username: str | None,
    first_name: str | None,
    last_name: str | None,
) -> User:
    session = s.session

    result = await session.execute(
        select(User).where(User.telegram_id == telegram_id)
    )
    user = result.scalar_one_or_none()

    if user is None:
        user = User(
            telegram_id=telegram_id,
            username=username,
            first_name=first_name,
            last_name=last_name,
        )
        session.add(user)
    else:
        user.username = username
        user.first_name = first_name
        user.last_name = last_name

    await session.flush()
    return user
