from ninja import Router

from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from django.shortcuts import get_object_or_404

from mentor.core.decorators import tvm_uid_required

from .constants import DEFAULT_USER_SETTINGS
from .schemas import UserIn, UserOut, UserPartialIn, UserSettingsIn, UserSettingsOut

User = get_user_model()

router = Router()


@router.post("/profile/", response=UserOut, summary="Создать пользователя")
@tvm_uid_required
def create_profile(request, payload: UserIn):
    return User.objects.create(
        **payload.dict(), yauid=request.tvm_uid, password=make_password(None)
    )


@router.get("/profile/", response=UserOut, summary="Получить пользователя")
@tvm_uid_required
def retrieve_profile(request):
    return get_object_or_404(User, yauid=request.tvm_uid)


@router.patch("/profile/", response=UserOut, summary="Обновить пользователя")
@tvm_uid_required
def update_profile(request, payload: UserPartialIn):
    user = get_object_or_404(User, yauid=request.tvm_uid)

    for key, value in payload.dict().items():
        setattr(user, key, value)

    user.save()

    return user


@router.get(
    "/settings/", response=UserSettingsOut, summary="Получить настройки пользователя"
)
def retrieve_user_settings(request):
    user = get_object_or_404(User, pk=request.user.pk)

    if user.settings:
        return user.settings

    return DEFAULT_USER_SETTINGS


@router.patch(
    "/settings/", response=UserSettingsOut, summary="Обновить настройки пользователя"
)
def update_user_settings(request, payload: UserSettingsIn):
    user = get_object_or_404(User, pk=request.user.pk)

    user.settings = payload.dict()

    user.save()

    return user.settings
