from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver

from .models import ProjectBrief
from .notifications import send_brief_status_email, send_new_brief_admin_email


@receiver(pre_save, sender=ProjectBrief)
def capture_previous_status(sender, instance, **kwargs):
    if instance.pk:
        try:
            instance._previous_status = ProjectBrief.objects.values_list(
                "status", flat=True
            ).get(pk=instance.pk)
        except ProjectBrief.DoesNotExist:
            instance._previous_status = None
    else:
        instance._previous_status = None


@receiver(post_save, sender=ProjectBrief)
def handle_brief_notifications(sender, instance, created, **kwargs):
    if created:
        send_new_brief_admin_email(instance)
        return
    previous_status = getattr(instance, "_previous_status", None)
    if previous_status and previous_status != instance.status:
        send_brief_status_email(instance, previous_status)
