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

from .models import CourseSessionGroup


@receiver(m2m_changed, sender=CourseSessionGroup.course_session.through)
def validate_course(sender, instance, action, reverse, model, pk_set, **kwargs):
    if action == "pre_add":
        course_sessions = model.objects.filter(pk__in=pk_set)
        for session in course_sessions:
            if session.course != instance.course:
                raise ValidationError(
                    "CourseSession does not match the Course of this Group."
                )
