from __future__ import annotations

from typing import Any, Optional

from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType

from ..models import AuditLog, Organization


User = get_user_model()


def log_action(
    *,
    organization: Organization,
    user: Optional[User],
    action: str,
    obj: Any,
    metadata: Optional[dict] = None,
) -> AuditLog:
    ct = ContentType.objects.get_for_model(obj.__class__)
    entry = AuditLog.objects.create(
        organization=organization,
        user=user,
        action=action,
        content_type=ct,
        object_id=getattr(obj, "pk", None) or getattr(obj, "id", None),
        metadata=metadata or {},
    )
    return entry

