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

from core.audit import create_audit_log, serialize_instance


@receiver(pre_save)
def audit_pre_save(sender, instance, **kwargs):
    if sender._meta.app_label not in {"accounts", "business", "inventory", "sales", "finance"}:
        return
    if not getattr(instance, "pk", None):
        return
    try:
        current = sender.objects.get(pk=instance.pk)
    except sender.DoesNotExist:
        instance._audit_old_values = {}
        return
    instance._audit_old_values = serialize_instance(current)


@receiver(post_save)
def audit_post_save(sender, instance, created, **kwargs):
    if sender._meta.app_label not in {"accounts", "business", "inventory", "sales", "finance"}:
        return
    new_values = serialize_instance(instance)
    if created:
        create_audit_log("create", instance, old_values={}, new_values=new_values)
        return
    old_values = getattr(instance, "_audit_old_values", {})
    create_audit_log("update", instance, old_values=old_values, new_values=new_values)


@receiver(pre_delete)
def audit_pre_delete(sender, instance, **kwargs):
    if sender._meta.app_label not in {"accounts", "business", "inventory", "sales", "finance"}:
        return
    old_values = serialize_instance(instance)
    create_audit_log("delete", instance, old_values=old_values, new_values={})
