# 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.
    Security Note: This prioritizes REMOTE_ADDR unless it appears to be a proxy.
    To be truly secure, configure TRUSTED_PROXIES in settings.
    """
    remote_addr = request.META.get('REMOTE_ADDR')
    x_forwarded = request.META.get('HTTP_X_FORWARDED_FOR')

    if x_forwarded:
        # Get the first IP in the list (the original client)
        client_ip = x_forwarded.split(',')[0].strip()
        # Only trust it if REMOTE_ADDR is an internal/proxy address
        # (Very basic check for 127.0.0.1, 10.*, 192.168.*, 172.16-31.*)
        if any(remote_addr.startswith(p) for p in ['127.0.0.1', '10.', '192.168.', '172.']):
             return client_ip
             
    return 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,
            company=getattr(request, 'company', 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
