"""Read-only query selectors for the audit app."""

from __future__ import annotations

from datetime import datetime

from django.db.models import QuerySet

from simorgh.apps.audit.models import AuditLog

__all__ = [
    "list_audit_log",
    "get_audit_entry",
]


def list_audit_log(
    tenant_id: int,
    *,
    resource_type: str | None = None,
    resource_id: str | None = None,
    actor_id: int | None = None,
    action: str | None = None,
    from_dt: datetime | None = None,
    to_dt: datetime | None = None,
    limit: int = 200,
) -> QuerySet:
    """Return AuditLog entries for a tenant, newest first.

    All filter parameters are optional and combined with AND semantics.

    Args:
        tenant_id:     Scope to this tenant (required).
        resource_type: Filter by resource type, e.g. ``"crm.Contact"``.
        resource_id:   Filter by the specific resource PK string.
        actor_id:      Filter by the acting user's PK.
        action:        Filter by action string, e.g. ``"update"``.
        from_dt:       Include entries at or after this datetime.
        to_dt:         Include entries at or before this datetime.
        limit:         Maximum number of entries to return (default 200).
    """
    qs = AuditLog.objects.filter(tenant_id=tenant_id)

    if resource_type:
        qs = qs.filter(resource_type=resource_type)
    if resource_id:
        qs = qs.filter(resource_id=resource_id)
    if actor_id is not None:
        qs = qs.filter(actor_id=actor_id)
    if action:
        qs = qs.filter(action=action)
    if from_dt:
        qs = qs.filter(created_at__gte=from_dt)
    if to_dt:
        qs = qs.filter(created_at__lte=to_dt)

    return qs.order_by("-created_at")[:limit]


def get_audit_entry(entry_id: int, tenant_id: int) -> AuditLog:
    """Return a single AuditLog entry scoped to a tenant.

    Raises ``AuditLog.DoesNotExist`` when not found.
    """
    return AuditLog.objects.get(pk=entry_id, tenant_id=tenant_id)
