"""当前用户与用户分页查询。"""

from __future__ import annotations

from flask import request
from sqlalchemy import select

from dms.api.v1.blueprint import api_v1
from dms.common.errors import AuthenticationError, InvalidArgumentError
from dms.common.pagination import PageRequest
from dms.common.response import success_response
from dms.extensions import db
from dms.models import User
from dms.security.auth_context import get_auth_context
from dms.security.decorators import admin_required, bearer_auth_required
from dms.services.user_service import list_users, parse_string_id, user_summary


def _integer_query(name: str, default: int) -> int:
    raw_value = request.args.get(name)
    if raw_value is None or raw_value == "":
        return default
    try:
        return int(raw_value)
    except ValueError as exc:
        raise InvalidArgumentError(f"{name}必须是整数") from exc


def _boolean_query(name: str, default: bool) -> bool:
    raw_value = request.args.get(name)
    if raw_value is None or raw_value == "":
        return default
    normalized = raw_value.lower()
    if normalized not in {"true", "false"}:
        raise InvalidArgumentError(f"{name}必须是true或false")
    return normalized == "true"


@api_v1.get("/users/me")
@bearer_auth_required
def current_user():
    context = get_auth_context()
    user = db.session.scalar(
        select(User).where(User.id == context.user_id, User.is_deleted.is_(False))
    )
    if user is None:
        raise AuthenticationError()
    return success_response(user_summary(user))


@api_v1.get("/users")
@bearer_auth_required
@admin_required
def users():
    page_request = PageRequest(
        page=_integer_query("page", 1),
        page_size=_integer_query("pageSize", 20),
    )
    data = list_users(
        organization_id=parse_string_id(
            request.args.get("organizationId"),
            name="organizationId",
        ),
        include_descendants=_boolean_query("includeDescendants", False),
        keyword=request.args.get("keyword"),
        status=request.args.get("status"),
        page_request=page_request,
    )
    return success_response(data)
