# accounts/audit.py
"""
Thin helper to log user actions. Import and call log_action() from any view.
"""
from .models import AuditLog


def get_client_ip(request):
    """Extract the real client IP from the request."""
    x_forwarded = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded:
        return x_forwarded.split(',')[0].strip()
    return request.META.get('REMOTE_ADDR')


def log_action(request, action, target='', extra=None):
    """
    Create an AuditLog entry.

    Usage:
        from accounts.audit import log_action
        log_action(request, 'add_product', target=f'Product: {product.name}')
    """
    try:
        AuditLog.objects.create(
            user=request.user if request.user.is_authenticated else None,
            action=action,
            target=target,
            ip_address=get_client_ip(request),
            extra=extra or {},
        )
    except Exception:
        # Audit logging must never crash the main app
        pass
