"""
User service routes for Memos-style backend.
"""

from typing import List

from fastapi import APIRouter, Body, Depends, HTTPException

from common.memos_core.schemas import (
    UserCreate,
    UserUpdate,
    UserResponse,
)
from common.memos_core.services import get_user_service


router = APIRouter(prefix="/users")


@router.get("", summary="List users", response_model=List[UserResponse])
async def list_users(user_service=Depends(get_user_service)):
    try:
        return await user_service.list_users()
    except Exception as exc:  # pragma: no cover
        raise HTTPException(status_code=500, detail=str(exc)) from exc


@router.post("", summary="Create user", response_model=UserResponse)
async def create_user(
    payload: dict = Body(default_factory=dict),
    user_service=Depends(get_user_service),
):
    try:
        # Accept both REST payload and Connect/proto-like envelope.
        # REST: { "email": "...", "password": "..." }
        # Possible envelope: { "user": { ... } } or other shapes.
        raw = payload.get("user") if isinstance(payload, dict) else None
        raw = raw if isinstance(raw, dict) else payload
        user_create = UserCreate(**(raw or {}))
        return await user_service.create_user(user_create)
    except Exception as exc:  # pragma: no cover
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@router.post("/settings", summary="List user settings (Connect compatibility)")
async def list_user_settings_connect_compat(payload: dict = Body(default_factory=dict)):  # noqa: B008
    """
    Connect RPC UserService/ListUserSettings is proxied as:
      POST /api/v1/users/settings

    The real Memos API returns a ListUserSettingsResponse with `settings`, `next_page_token`, `total_size`.
    For stub backend, return empty list to let frontend proceed.
    """
    _ = payload
    return {
        "settings": [],
        "next_page_token": "",
        "total_size": 0,
    }


@router.get("/{user_id}", summary="Get user by ID", response_model=UserResponse)
async def get_user(user_id: str, user_service=Depends(get_user_service)):
    try:
        return await user_service.get_user(user_id)
    except Exception as exc:  # pragma: no cover
        raise HTTPException(status_code=404, detail=str(exc)) from exc


@router.patch("/{user_id}", summary="Update user", response_model=UserResponse)
async def update_user(
    user_id: str,
    payload: UserUpdate,
    user_service=Depends(get_user_service),
):
    try:
        return await user_service.update_user(user_id, payload)
    except Exception as exc:  # pragma: no cover
        raise HTTPException(status_code=400, detail=str(exc)) from exc


