# xll_kit/services/mixins/audit_mixin.py
from xll_kit.core.audit.diff import diff_model
from xll_kit.core.audit.logger import log_audit_object, log_audit_fields


class AuditMixin:
    def _should_audit(self, obj) -> bool:
        """三层检查策略（从上到下）"""
        # 1. 检查实例级别（最高优先级）
        if hasattr(obj, '_audit_disabled') and obj._audit_disabled:
            return False

        # 2. 检查模型级别配置
        model_audit_enabled = getattr(obj, '_audit_enabled', None)
        model_audit_disabled = getattr(obj, '_audit_disabled', None)

        if model_audit_disabled:
            return False
        if model_audit_enabled is not None:
            return model_audit_enabled

        # 3. 检查服务级别配置（最低优先级）
        if hasattr(self, 'audit_enabled'):
            return self.audit_enabled

        return True  # 默认审计

    def _audit_create(self, session, obj, user=None):
        # 如果模型定义了 audit config 才记录
        if self._should_audit(obj):
            log_audit_object(session, obj, action="create", user=user)

    def _audit_update(self, session, obj, before, after, user=None):
        if not self._should_audit(obj):
            return

        diff = diff_model(before, after,
                          include=getattr(obj, "_audit_include", None),
                          exclude=getattr(obj, "_audit_exclude", None))
        if diff:
            log_audit_object(session, obj, action="update", data=diff, user=user)
            # 如果需要字段级别的详细审计
            if getattr(obj, '_audit_fields_detail', False):
                log_audit_fields(session, obj, diff, user=user)

    def _audit_delete(self, session, obj, user=None):
        if self._should_audit(obj):
            log_audit_object(session, obj, action="delete", user=user)
