from django.contrib.auth.hashers import make_password
from rest_framework import exceptions, permissions, status, views
from rest_framework.generics import get_object_or_404

from core.http import views as http_views
from core.http.models import User

from ..serializers import ChangePasswordSerializer


class ChangePasswordView(views.APIView, http_views.ApiResponse):
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        user = request.user

        if user is None:
            raise exceptions.ValidationError(
                {"status": False, "message": "Foydalanuvchi topilmadi"}
            )
        serializer = ChangePasswordSerializer(data=request.data)
        if serializer.is_valid():
            if user.check_password(request.data["old_password"]):
                user.password = make_password(serializer.data["new_password"])
                user.save()
                return http_views.ApiResponse().success(
                    "Parol muvaffaqiyatli o'zgartirildi",
                    status_code=status.HTTP_200_OK,
                )
            return http_views.ApiResponse().error(
                "Noto'g'ri eski parol", status_code=status.HTTP_400_BAD_REQUEST
            )
        return http_views.ApiResponse().error(
            serializer.errors, status_code=status.HTTP_400_BAD_REQUEST
        )
