from django.db.models.signals import pre_save, post_save, post_delete
from django.dispatch import receiver
from .models import Customernote, ActivityLog
from django.forms.models import model_to_dict
from datetime import date, datetime

def serialize_data(instance):
    """ Convert model instance to dict and ensure date fields are JSON serializable """
    data = model_to_dict(instance)
    for key, value in data.items():
        if isinstance(value, (datetime, date)):
            data[key] = value.isoformat()  # Convert to string format
    return data

# Store old instance data BEFORE saving
@receiver(pre_save, sender=Customernote)
def capture_old_data(sender, instance, **kwargs):
    """ Store old data before update """
    if instance.pk:  # Only if object already exists
        try:
            instance._old_data = serialize_data(Customernote.objects.get(pk=instance.pk))
        except Customernote.DoesNotExist:
            instance._old_data = None  # If it's a new record, no old data

# Log Create & Update AFTER saving
@receiver(post_save, sender=Customernote)
def log_note_save(sender, instance, created, **kwargs):
    old_data = getattr(instance, '_old_data', None) if not created else None
    new_data = serialize_data(instance)

    # Log only if old and new data are different (for updates)
    if created or old_data != new_data:
        ActivityLog.objects.create(
            model_name='Customernote',
            user=instance.assigned_to, 
            action="Created" if created else "Updated",
            instance_id=instance.id,
            instance_str=f"Note '{instance.note[:50]}' was created." if created else f"Note '{instance.note[:50]}' was updated.",
            old_data=old_data,  
            new_data=new_data
        )

# Log Delete
@receiver(post_delete, sender=Customernote)
def log_note_delete(sender, instance, **kwargs):
    ActivityLog.objects.create(
        model_name='Customernote',
        user=instance.assigned_to,
        action="Deleted",
        instance_id=instance.id,
        instance_str=f"Note '{instance.note[:50]}...' was deleted.",
        old_data=serialize_data(instance),
        new_data=None
    )
