from django.core.exceptions import ValidationError
from django.db.models.signals import m2m_changed
from django.dispatch import receiver

from .models import LearningMentor


@receiver(m2m_changed, sender=LearningMentor.participants.through)
def validate_student(sender, instance, action, reverse, model, pk_set, **kwargs):
    if action == "pre_add":
        participants = model.objects.filter(pk__in=pk_set)
        for participant in participants:
            if participant.course_session.course != instance.course:
                raise ValidationError(
                    "Participant (CourseSessionUser) does not match the course for this mentor."
                )
