"""Current-user profile routes (separate from ``/api/auth`` magic-link and MFA)."""
from __future__ import annotations

from typing import Optional

from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from src.core.database import get_db
from src.core.exceptions import NotFoundError
from src.domain.auth.models import User
from src.domain.auth.repository import UserRepository
from src.domain.auth.router import get_current_user
from src.domain.auth.schemas import UserProfileResponse, UserProfileUpdate

router = APIRouter(prefix="/api/users", tags=["users"])

_ALLOWED_PATCH_KEYS = frozenset(
    {"first_name", "last_name", "display_name", "phone", "company", "avatar_url", "ui_theme"}
)


def _normalize_str(value: Optional[str]) -> Optional[str]:
    if value is None:
        return None
    s = value.strip()
    return s if s else None


@router.patch("/me", response_model=UserProfileResponse)
async def patch_current_user_profile(
    body: UserProfileUpdate,
    user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """Update the authenticated user's profile. Email change is not supported here."""
    raw = body.model_dump(exclude_unset=True)
    kwargs = {}
    for key in _ALLOWED_PATCH_KEYS:
        if key not in raw:
            continue
        val = raw[key]
        if key == "ui_theme":
            kwargs[key] = val
        else:
            kwargs[key] = _normalize_str(val) if isinstance(val, str) else val

    if not kwargs:
        u = await UserRepository(db).get_by_id(user.id)
        if not u:
            raise NotFoundError("User not found")
        return UserProfileResponse.model_validate(u)

    updated = await UserRepository(db).update_profile(user.id, **kwargs)
    if not updated:
        raise NotFoundError("User not found")
    return UserProfileResponse.model_validate(updated)
