from django.http.response import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.db.models import Q
from Auth.models import Profile, ProfileRole

import N3wtSchool.mailManager as mailer
from N3wtSchool import bdd
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.exceptions import NotFound
import uuid
import logging

# Ajouter un logger pour debug
logger = logging.getLogger(__name__)

class SendEmailView(APIView):
    """
    API pour envoyer des emails aux parents et professeurs.
    """
    def post(self, request):
        # Ajouter du debug
        logger.info(f"Request data received: {request.data}")
        logger.info(f"Request content type: {request.content_type}")

        data = request.data
        recipients = data.get('recipients', [])
        cc = data.get('cc', [])
        bcc = data.get('bcc', [])
        subject = data.get('subject', 'Notification')
        message = data.get('message', '')
        establishment_id = data.get('establishment_id', '')

        # Debug des données reçues
        logger.info(f"Recipients: {recipients} (type: {type(recipients)})")
        logger.info(f"CC: {cc} (type: {type(cc)})")
        logger.info(f"BCC: {bcc} (type: {type(bcc)})")
        logger.info(f"Subject: {subject}")
        logger.info(f"Message length: {len(message) if message else 0}")
        logger.info(f"Establishment ID: {establishment_id}")

        if not recipients or not message:
            logger.error("Recipients or message missing")
            logger.error(f"Recipients empty: {not recipients}, Message empty: {not message}")
            logger.error(f"Recipients value: '{recipients}', Message value: '{message}'")
            return Response({'error': 'Les destinataires et le message sont requis.'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # Récupérer la connexion SMTP
            logger.info("Tentative de récupération de la connexion SMTP...")
            connection = mailer.getConnection(establishment_id)
            logger.info(f"Connexion SMTP récupérée: {connection}")

            # Envoyer l'email
            logger.info("Tentative d'envoi de l'email...")
            result = mailer.sendMail(
                subject=subject,
                message=message,
                recipients=recipients,
                cc=cc,
                bcc=bcc,
                attachments=[],
                connection=connection
            )
            logger.info(f"Email envoyé avec succès: {result}")
            return result
        except NotFound as e:
            logger.error(f"NotFound error: {str(e)}")
            return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            logger.error(f"Exception during email sending: {str(e)}")
            logger.error(f"Exception type: {type(e)}")
            import traceback
            logger.error(f"Traceback: {traceback.format_exc()}")
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

def search_recipients(request):
    """
    API pour rechercher des destinataires en fonction d'un terme de recherche et d'un établissement.
    """
    query = request.GET.get('q', '').strip()  # Récupérer le terme de recherche depuis les paramètres GET
    establishment_id = request.GET.get('establishment_id', None)  # Récupérer l'ID de l'établissement

    if not query:
        return JsonResponse([], safe=False)  # Retourner une liste vide si aucun terme n'est fourni

    if not establishment_id:
        return JsonResponse({'error': 'establishment_id est requis'}, safe=False, status=status.HTTP_400_BAD_REQUEST)

    # Rechercher dans les champs pertinents (nom, prénom, email) et filtrer par establishment_id
    profiles = Profile.objects.filter(
        Q(first_name__icontains=query) |
        Q(last_name__icontains=query) |
        Q(email__icontains=query),
        roles__establishment_id=establishment_id,  # Utiliser 'roles' au lieu de 'profilerole'
        roles__is_active=True  # Filtrer uniquement les ProfileRole actifs
    ).distinct()

    # Construire la réponse avec les rôles associés
    results = []
    for profile in profiles:
        profile_roles = ProfileRole.objects.filter(
            profile=profile,
            establishment_id=establishment_id,
            is_active=True  # Inclure uniquement les ProfileRole actifs
        ).values(
            'id', 'role_type', 'establishment__name', 'is_active'
        )
        results.append({
            'id': profile.id,
            'first_name': profile.first_name,
            'last_name': profile.last_name,
            'email': profile.email,
            'roles': list(profile_roles)  # Inclure tous les rôles actifs associés pour cet établissement
        })

    return JsonResponse(results, safe=False)
