from app.core.jwt_denylist import bump_auth_epoch
from app.core.security import hash_password, verify_password
from app.modules.auth.service import revoke_user_refresh_family
from app.modules.media.service import upload_user_avatar
from app.modules.users import repository
from app.modules.users.models import User


def get_me(user: User) -> dict:
    profile = repository.get_profile(user.id)
    return {"user": user, "profile": profile}


def update_me(user: User, display_name: str | None) -> dict:
    profile = repository.update_profile(user.id, display_name=display_name)
    return {"user": user, "profile": profile}


def upload_avatar(user: User, content: bytes) -> dict:
    avatar_url = upload_user_avatar(user.id, content)
    profile = repository.update_profile(user.id, avatar_url=avatar_url)
    return {"user": user, "profile": profile}


def change_password(user: User, current_password: str, new_password: str) -> None:
    if not verify_password(current_password, user.password_hash):
        raise ValueError("INVALID_CURRENT_PASSWORD")
    user.password_hash = hash_password(new_password)
    repository.update_user(user)
    bump_auth_epoch(user.id)
    revoke_user_refresh_family(user.id)
