from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from .models import SMTPSettings
from .serializers import SMTPSettingsSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated

class SMTPSettingsView(APIView):
    permission_classes = [IsAuthenticated]
    """
    API pour gérer les paramètres SMTP.
    """

    @swagger_auto_schema(
        operation_description="Récupérer les paramètres SMTP pour un établissement spécifique ou tous les paramètres si aucun ID n'est fourni",
        manual_parameters=[
            openapi.Parameter(
                'establishment_id',
                openapi.IN_QUERY,
                description="ID de l'établissement (facultatif)",
                type=openapi.TYPE_INTEGER,
                required=False
            )
        ],
        responses={
            200: SMTPSettingsSerializer(many=True),
            404: openapi.Response(description="Aucun paramètre SMTP trouvé."),
            500: openapi.Response(description="Erreur interne du serveur."),
        },
    )
    def get(self, request):
        establishment_id = request.query_params.get('establishment_id')

        try:
            if establishment_id:
                # Récupérer les paramètres SMTP pour un établissement spécifique
                smtp_settings = SMTPSettings.objects.filter(establishment_id=establishment_id).first()
                if not smtp_settings:
                    return Response(
                        {'error': f"Aucun paramètre SMTP trouvé pour l'établissement {establishment_id}."},
                        status=status.HTTP_404_NOT_FOUND
                    )
                serializer = SMTPSettingsSerializer(smtp_settings)
                return Response(serializer.data, status=status.HTTP_200_OK)
            else:
                # Récupérer tous les paramètres SMTP
                smtp_settings = SMTPSettings.objects.all()
                if not smtp_settings.exists():
                    return Response(
                        {'error': "Aucun paramètre SMTP trouvé."},
                        status=status.HTTP_404_NOT_FOUND
                    )
                serializer = SMTPSettingsSerializer(smtp_settings, many=True)
                return Response(serializer.data, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @swagger_auto_schema(
        operation_description="Créer ou mettre à jour les paramètres SMTP pour un établissement spécifique",
        request_body=SMTPSettingsSerializer,
        responses={
            200: SMTPSettingsSerializer(),
            400: openapi.Response(description="Données invalides."),
            500: openapi.Response(description="Erreur interne du serveur."),
        },
    )
    def post(self, request):
        data = request.data
        try:
            smtp_settings = SMTPSettings.objects.first()
            if smtp_settings:
                serializer = SMTPSettingsSerializer(smtp_settings, data=data)
            else:
                serializer = SMTPSettingsSerializer(data=data)

            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_200_OK)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)