from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.views import APIView
from django.contrib.auth.models import User
from rest_framework_simplejwt.tokens import RefreshToken

class CustomAuthToken(ObtainAuthToken):

    def post(self, request: Request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        refresh = RefreshToken.for_user(user)

        return {
            'refresh': str(refresh),
            'access': str(refresh.access_token),
        }
        #
        # token, created = Token.objects.get_or_create(user=user)
        # return Response({
        #     'token': token.key,
        #     'user_id': user.pk,
        #     'username': user.username
        # })


class RegisterView(APIView):

    def get(self, request: Request, *args, **kwargs):
        username = request.data.get("username", None)
        if not username:
            return Response({"message": "Username must not be empty"}, status=406)
        if User.objects.filter(username=username).exists():
            return Response({"message": "Username already taken"}, status=409)
        return Response({"message": "Username availiable"}, status=200)

    def post(self, request: Request, *args, **kwargs):
        username = request.data.get("username")
        if not username:
            return Response({"message": "Username must not be empty"}, status=406)
        if User.objects.filter(username=username).exists():
            return Response({"message": "Username already taken"}, status=409)
        password = request.data.get("password", None)
        if not password:
            return Response({"message": "Password must not be empty"}, status=406)
        try:
            user = User.objects.create_user(
                is_superuser=False,
                username=username,
                password=password
            )
            refresh = RefreshToken.for_user(user)
            return Response({
                'refresh': str(refresh),
                'access': str(refresh.access_token),
            }, status=200)
            # token, created = Token.objects.get_or_create(user=user)
            # return Response({
            #     'token': token.key,
            #     'user_id': user.pk,
            #     'username': user.username
            # }, status=200)
        except Exception as e:
            return Response({"message": "Something went wrong, registration is not completed", "error": e}, status=500)
