"""管理员用户 CRUD。"""

from fastapi import APIRouter, Query

from app.dependencies import AdminUser, DbSession
from app.schemas.admin_user import AdminUserCreate, AdminUserOut, AdminUserUpdate
from app.schemas.common import ApiResponse, PaginatedData
from app.services import admin_user as admin_user_service

router = APIRouter(prefix="/admin/users", tags=["管理-用户"])


@router.get("", response_model=ApiResponse[PaginatedData[AdminUserOut]])
async def list_users(
    _admin: AdminUser,
    db: DbSession,
    page: int = Query(1, ge=1, description="页码，从 1 开始"),
    page_size: int = Query(
        admin_user_service.DEFAULT_PAGE_SIZE,
        ge=1,
        le=admin_user_service.MAX_PAGE_SIZE,
        description="每页条数",
    ),
    username: str | None = Query(None, description="用户名模糊搜索"),
    device_serial: str | None = Query(None, description="设备码模糊搜索"),
    oem_id: int | None = Query(None, description="按所属 OEM 用户 ID 筛选"),
    agent_id: int | None = Query(None, description="按所属代理用户 ID 筛选"),
    role_id: int | None = Query(None, ge=0, le=3, description="按角色筛选"),
) -> ApiResponse[PaginatedData[AdminUserOut]]:
    users, total = await admin_user_service.list_users(
        db,
        page=page,
        page_size=page_size,
        username=username,
        device_serial=device_serial,
        oem_id=oem_id,
        agent_id=agent_id,
        role_id=role_id,
    )
    return ApiResponse(
        ok=True,
        message="",
        data=PaginatedData.build(
            [AdminUserOut.model_validate(u) for u in users],
            total=total,
            page=page,
            page_size=page_size,
        ),
    )


@router.post("", response_model=ApiResponse[AdminUserOut])
async def create_user(
    body: AdminUserCreate,
    admin: AdminUser,
    db: DbSession,
) -> ApiResponse[AdminUserOut]:
    try:
        user = await admin_user_service.create_user(db, body)
    except admin_user_service.AdminUserError as exc:
        return ApiResponse(ok=False, message=exc.message)

    return ApiResponse(
        ok=True,
        message="用户已创建",
        data=AdminUserOut.model_validate(user),
    )


@router.patch("/{user_id}", response_model=ApiResponse[AdminUserOut])
async def update_user(
    user_id: int,
    body: AdminUserUpdate,
    admin: AdminUser,
    db: DbSession,
) -> ApiResponse[AdminUserOut]:
    try:
        user = await admin_user_service.update_user(
            db,
            user_id,
            body,
            actor_id=admin.id,
        )
    except admin_user_service.AdminUserError as exc:
        return ApiResponse(ok=False, message=exc.message)

    return ApiResponse(
        ok=True,
        message="用户已更新",
        data=AdminUserOut.model_validate(user),
    )


@router.post("/{user_id}/clear-device-serial", response_model=ApiResponse[AdminUserOut])
async def clear_device_serial(
    user_id: int,
    _admin: AdminUser,
    db: DbSession,
) -> ApiResponse[AdminUserOut]:
    try:
        user = await admin_user_service.clear_device_serial(db, user_id)
    except admin_user_service.AdminUserError as exc:
        return ApiResponse(ok=False, message=exc.message)

    return ApiResponse(
        ok=True,
        message="设备已解绑",
        data=AdminUserOut.model_validate(user),
    )


@router.delete("/{user_id}", response_model=ApiResponse[None])
async def delete_user(
    user_id: int,
    admin: AdminUser,
    db: DbSession,
) -> ApiResponse[None]:
    try:
        await admin_user_service.delete_user(db, user_id, actor_id=admin.id)
    except admin_user_service.AdminUserError as exc:
        return ApiResponse(ok=False, message=exc.message)

    return ApiResponse(ok=True, message="用户已删除")
