"""Audit service — append-only Loyalty audit trail."""
from __future__ import annotations

from typing import Any
from uuid import UUID

from sqlalchemy.ext.asyncio import AsyncSession

from app.models.foundation import LoyaltyAuditLog
from app.models.types import AuditAction
from app.repositories.foundation import LoyaltyAuditLogRepository


class AuditService:
    def __init__(self, session: AsyncSession) -> None:
        self.session = session
        self.repo = LoyaltyAuditLogRepository(session)

    async def record(
        self,
        *,
        tenant_id: UUID,
        entity_type: str,
        entity_id: UUID,
        action: AuditAction,
        actor_user_id: str | None = None,
        changes: dict[str, Any] | None = None,
        message: str | None = None,
        commit: bool = False,
    ) -> LoyaltyAuditLog:
        entry = LoyaltyAuditLog(
            tenant_id=tenant_id,
            entity_type=entity_type,
            entity_id=entity_id,
            action=action,
            actor_user_id=actor_user_id,
            changes=changes,
            message=message,
        )
        await self.repo.add(entry)
        if commit:
            await self.session.commit()
            await self.session.refresh(entry)
        return entry

    async def list_for_entity(
        self, tenant_id: UUID, entity_type: str, entity_id: UUID, *, limit: int = 100
    ):
        return await self.repo.list_for_entity(
            tenant_id, entity_type, entity_id, limit=limit
        )
