from django.http.response import JsonResponse
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.parsers import MultiPartParser, FormParser, JSONParser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status

from Subscriptions.serializers import RegistrationParentFileTemplateSerializer
from Subscriptions.models import (
    RegistrationParentFileTemplate
)
from N3wtSchool import bdd
import logging
import Subscriptions.util as util

logger = logging.getLogger(__name__)

class RegistrationParentFileTemplateView(APIView):
    @swagger_auto_schema(
        operation_description="Récupère tous les templates parents pour un établissement donné",
        manual_parameters=[
            openapi.Parameter(
                'establishment_id',
                openapi.IN_QUERY,
                description="ID de l'établissement",
                type=openapi.TYPE_INTEGER,
                required=True
            )
        ],
        responses={200: RegistrationParentFileTemplateSerializer(many=True)}
    )
    def get(self, request):
        establishment_id = request.GET.get('establishment_id')
        if not establishment_id:
            return Response({'error': "Paramètre 'establishment_id' requis"}, status=status.HTTP_400_BAD_REQUEST)

        # Filtrer les templates parents liés à l'établissement via master.groups.establishment
        templates = RegistrationParentFileTemplate.objects.filter(
            master__groups__establishment__id=establishment_id
        ).distinct()
        serializer = RegistrationParentFileTemplateSerializer(templates, many=True)
        return Response(serializer.data)

    @swagger_auto_schema(
        operation_description="Crée un nouveau template d'inscription",
        request_body=RegistrationParentFileTemplateSerializer,
        responses={
            201: RegistrationParentFileTemplateSerializer,
            400: "Données invalides"
        }
    )
    def post(self, request):
        serializer = RegistrationParentFileTemplateSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class RegistrationParentFileTemplateSimpleView(APIView):
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    @swagger_auto_schema(
        operation_description="Récupère un template d'inscription spécifique",
        responses={
            200: RegistrationParentFileTemplateSerializer,
            404: "Template non trouvé"
        }
    )
    def get(self, request, id):
        template = bdd.getObject(_objectName=RegistrationParentFileTemplate, _columnName='id', _value=id)
        if template is None:
            return JsonResponse({"errorMessage":'Le template d\'inscription n\'a pas été trouvé'}, safe=False, status=status.HTTP_404_NOT_FOUND)
        serializer = RegistrationParentFileTemplateSerializer(template)
        return JsonResponse(serializer.data, safe=False)

    @swagger_auto_schema(
        operation_description="Met à jour un template d'inscription existant",
        request_body=RegistrationParentFileTemplateSerializer,
        responses={
            200: RegistrationParentFileTemplateSerializer,
            400: "Données invalides",
            404: "Template non trouvé"
        }
    )
    def put(self, request, id):
        payload, resp = util.build_payload_from_request(request)
        if resp is not None:
            return resp

        template = bdd.getObject(_objectName=RegistrationParentFileTemplate, _columnName='id', _value=id)
        if template is None:
            return JsonResponse({'erreur': 'Le template d\'inscription n\'a pas été trouvé'}, safe=False, status=status.HTTP_404_NOT_FOUND)

        serializer = RegistrationParentFileTemplateSerializer(template, data=payload, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({'message': 'Template mis à jour avec succès', 'data': serializer.data}, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @swagger_auto_schema(
        operation_description="Supprime un template d'inscription",
        responses={
            204: "Suppression réussie",
            404: "Template non trouvé"
        }
    )
    def delete(self, request, id):
        template = bdd.getObject(_objectName=RegistrationParentFileTemplate, _columnName='id', _value=id)
        if template is not None:
            # Suppression du fichier PDF associé
            if template.file and template.file.name:
                template.file.delete(save=False)
            template.delete()
            return JsonResponse({'message': 'La suppression du template a été effectuée avec succès'}, safe=False, status=status.HTTP_204_NO_CONTENT)
        else:
            return JsonResponse({'erreur': 'Le template n\'a pas été trouvé'}, safe=False, status=status.HTTP_404_NOT_FOUND)
