import jwt
from jwt.exceptions import ExpiredSignatureError, InvalidTokenError
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.contrib.auth import get_user_model
from .utils import generate_token_and_user_data

User = get_user_model()

@api_view(['POST'])
def signin_apple(request):
    try:
        id_token = request.data['id_token']
        email = request.data['email']
        full_name = request.data['full_name']

        # Verify the JWT token
        header = {'alg': 'ES256', 'kid': 'YOUR_APPLE_KEY_ID'}
        key = open('path/to/your/Apple-developer-cert.p8', 'rb').read()
        decoded_token = jwt.decode(id_token, key, audience='YOUR_APP_BUNDLE_ID', algorithms=['ES256'], options={'verify_aud': False})

        # Create a new user
        user, created = User.objects.get_or_create(
            email=email,
            defaults={
                'first_name': full_name.split()[0],
                'last_name': full_name.split()[1],
                'is_active': True,
            },
        )

        if created:
            user.save()

        # Generate a JWT token for the new user
        token_data = generate_token_and_user_data(user)

        return Response(token_data, status=status.HTTP_200_OK)

    except (KeyError, ExpiredSignatureError, InvalidTokenError) as e:
        return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)