from quart import Blueprint, jsonify, request
from sqlalchemy import or_, select

from scribe.auth import get_current_user_id, login_required
from scribe.models import async_session
from scribe.models.user import User

users_bp = Blueprint("users", __name__, url_prefix="/api/users")


@users_bp.route("/search", methods=["GET"])
@login_required
async def search_users():
    uid = get_current_user_id()
    q = (request.args.get("q") or "").strip()
    if len(q) < 2:
        return jsonify({"users": []})
    like = f"{q}%"
    async with async_session() as session:
        users = (await session.execute(
            select(User).where(
                User.id != uid,
                or_(User.username.ilike(like), User.email.ilike(like)),
            ).limit(10)
        )).scalars().all()
    return jsonify({"users": [
        {"id": u.id, "username": u.username}
        for u in users
    ]})
