from service.core.security import verify_password
from service.database.models import User
from ..utils import order_queryset

from ...api.dependencies import QueryParams
from .models import UserPublic, UserRegister


async def authenticate(*, username: str, password: str) -> User | None:
    db_user = await get_user_by_username(username=username)
    if not db_user:
        return None
    return db_user if verify_password(password, db_user.password) else None


async def get_user_by_email(*, email: str) -> User | None:
    return await User.filter(email=email).first()


async def get_user_by_username(*, username: str) -> User | None:
    return await User.filter(username=username).first()


async def get_users(filters: QueryParams) -> list[UserPublic]:
    queryset = User.all()
    if filters.q:
        queryset = queryset.filter(username__icontains=filters.q)
    queryset = order_queryset(queryset, filters, "-modified_at")
    return [
        UserPublic(id=u.id, username=u.username) for u in await queryset.offset(filters.offset).limit(filters.limit)
    ]


async def register_user(data: UserRegister) -> User:
    user_object = User(email=data.email, username=data.username)
    user_object.set_password(data.password)
    await user_object.save()
    await user_object.refresh_from_db()
    return user_object
