from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
import jwt
import datetime
import requests

@csrf_exempt
@api_view(['POST'])
def generate_jwt_token(request):
    # Vérifier la clé API
    api_key = request.headers.get('X-Auth-Token')
    if not api_key or api_key != settings.DOCUSEAL_JWT["API_KEY"]:
        return Response({'error': 'Invalid API key'}, status=status.HTTP_401_UNAUTHORIZED)

    # Récupérer les données de la requête
    user_email = request.data.get('user_email')
    documents_urls = request.data.get('documents_urls', [])
    id = request.data.get('id')  # Récupérer le id

    # Vérifier les données requises
    if not user_email:
        return Response({'error': 'User email is required'}, status=status.HTTP_400_BAD_REQUEST)

    # Utiliser la configuration JWT de DocuSeal depuis les settings
    jwt_secret = settings.DOCUSEAL_JWT['API_KEY']
    jwt_algorithm = settings.DOCUSEAL_JWT['ALGORITHM']
    expiration_delta = settings.DOCUSEAL_JWT['EXPIRATION_DELTA']

    # Définir le payload
    payload = {
        'user_email': user_email,
        'documents_urls': documents_urls,
        'template_id': id,  # Ajouter le id au payload
        'exp': datetime.datetime.utcnow() + expiration_delta  # Temps d'expiration du token
    }

    # Générer le token JWT
    token = jwt.encode(payload, jwt_secret, algorithm=jwt_algorithm)

    return Response({'token': token}, status=status.HTTP_200_OK)

@csrf_exempt
@api_view(['POST'])
def clone_template(request):
    # Vérifier la clé API
    api_key = request.headers.get('X-Auth-Token')
    if not api_key or api_key != settings.DOCUSEAL_JWT["API_KEY"]:
        return Response({'error': 'Invalid API key'}, status=status.HTTP_401_UNAUTHORIZED)

    # Récupérer les données de la requête
    document_id = request.data.get('templateId')
    email = request.data.get('email')
    is_required = request.data.get('is_required')
    print(f'test is required = {is_required}')

    # Vérifier les données requises
    if not document_id :
        return Response({'error': 'template ID is required'}, status=status.HTTP_400_BAD_REQUEST)

    # URL de l'API de DocuSeal pour cloner le template
    clone_url = f'https://docuseal.com/api/templates/{document_id}/clone'

    # Faire la requête pour cloner le template
    try:
        response = requests.post(clone_url, headers={
            'Content-Type': 'application/json',
            'X-Auth-Token': settings.DOCUSEAL_JWT['API_KEY']
        })

        if response.status_code != status.HTTP_200_OK:
            return Response({'error': 'Failed to clone template'}, status=response.status_code)

        data = response.json()

        if is_required:
            print(f'REQUIRED -> création dune submission')
            # URL de l'API de DocuSeal pour créer une submission
            submission_url = f'https://docuseal.com/api/submissions'

            # Faire la requête pour cloner le template
            try:
                clone_id = data['id']
                response = requests.post(submission_url, json={'template_id':clone_id, 'send_email': False, 'submitters': [{'email': email}]}, headers={
                    'Content-Type': 'application/json',
                    'X-Auth-Token': settings.DOCUSEAL_JWT['API_KEY']
                })

                if response.status_code != status.HTTP_200_OK:
                    return Response({'error': 'Failed to create submission'}, status=response.status_code)

                data = response.json()
                data[0]['id'] = clone_id
                print(f'DATA RESPONSE : {data[0]}')
                return Response(data[0], status=status.HTTP_200_OK)
            
            except requests.RequestException as e:
                return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else :
            print(f'NOT REQUIRED -> on ne crée pas de submission')
            return Response(data, status=status.HTTP_200_OK)

    except requests.RequestException as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@csrf_exempt
@api_view(['DELETE'])
def remove_template(request, id):
    # Vérifier la clé API
    api_key = request.headers.get('X-Auth-Token')
    if not api_key or api_key != settings.DOCUSEAL_JWT["API_KEY"]:
        return Response({'error': 'Invalid API key'}, status=status.HTTP_401_UNAUTHORIZED)

    # URL de l'API de DocuSeal pour cloner le template
    clone_url = f'https://docuseal.com/api/templates/{id}'

    # Faire la requête pour cloner le template
    try:
        response = requests.delete(clone_url, headers={
            'X-Auth-Token': settings.DOCUSEAL_JWT['API_KEY']
        })

        if response.status_code != status.HTTP_200_OK:
            return Response({'error': 'Failed to remove template'}, status=response.status_code)

        data = response.json()
        return Response(data, status=status.HTTP_200_OK)

    except requests.RequestException as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@csrf_exempt
@api_view(['GET'])
def download_template(request, slug):
    # Vérifier la clé API
    api_key = request.headers.get('X-Auth-Token')
    if not api_key or api_key != settings.DOCUSEAL_JWT["API_KEY"]:
        return Response({'error': 'Invalid API key'}, status=status.HTTP_401_UNAUTHORIZED)

    # Vérifier les données requises
    if not slug :
        return Response({'error': 'slug is required'}, status=status.HTTP_400_BAD_REQUEST)

    # URL de l'API de DocuSeal pour cloner le template
    download_url = f'https://docuseal.com/submitters/{slug}/download'

    # Faire la requête pour cloner le template
    try:
        response = requests.get(download_url, headers={
            'Content-Type': 'application/json',
            'X-Auth-Token': settings.DOCUSEAL_JWT['API_KEY']
        })

        if response.status_code != status.HTTP_200_OK:
            return Response({'error': 'Failed to download template'}, status=response.status_code)

        data = response.json()
        return Response(data, status=status.HTTP_200_OK)

    except requests.RequestException as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
