from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from .models import Appointment
from .services import EmailService
from scheduler.models import Business


@receiver(post_save, sender=Appointment)
def appointment_created_or_updated(sender, instance, created, **kwargs):
    if created:
        try:
            business = Business.objects.get(user=instance.user)
            EmailService.send_appointment_confirmation(instance, business)
            EmailService.send_owner_notification(instance, business)
        except Business.DoesNotExist:
            pass
        except Exception as e:
            print(f"Error sending notifications: {e}")


@receiver(pre_save, sender=Appointment)
def appointment_status_changed(sender, instance, **kwargs):
    if instance.pk:
        try:
            old_appointment = Appointment.objects.get(pk=instance.pk)
            if old_appointment.status != instance.status and instance.status == 'cancelled':
                try:
                    business = Business.objects.get(user=instance.user)
                    EmailService.send_appointment_cancellation(instance, business)
                except Business.DoesNotExist:
                    pass
                except Exception as e:
                    print(f"Error sending cancellation: {e}")
        except Appointment.DoesNotExist:
            pass