"""GDPR audit logging service.

⚠️ AUTO-GENERATED BY PRISM — DO NOT EDIT
This file is regenerated on every `prisme generate`.
"""

from __future__ import annotations

import logging
from datetime import datetime, timezone
from typing import Any

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from {{ package_name }}.privacy.audit_log_model import PrivacyAuditLog

logger = logging.getLogger(__name__)


class AuditService:
    """Service for recording and querying GDPR audit log entries."""

    def __init__(self, session: AsyncSession) -> None:
        self.session = session

    async def log(
        self,
        *,
        operation: str,
        model_name: str,
        record_id: str | None = None,
        field_name: str | None = None,
        user_id: str | None = None,
        ip_address: str | None = None,
        details: str | None = None,
    ) -> PrivacyAuditLog:
        """Record an audit log entry.

        Args:
            operation: The operation type (read, create, update, delete, export, erase).
            model_name: The model/table that was accessed.
            record_id: The primary key of the accessed record.
            field_name: Specific field accessed (for field-level auditing).
            user_id: The user who performed the operation.
            ip_address: Client IP address.
            details: Additional context or change description.
        """
        entry = PrivacyAuditLog(
            timestamp=datetime.now(timezone.utc),
            user_id=user_id,
            operation=operation,
            model_name=model_name,
            record_id=str(record_id) if record_id is not None else None,
            field_name=field_name,
            ip_address=ip_address,
            details=details,
        )
        self.session.add(entry)
        await self.session.flush()
        return entry

    async def query(
        self,
        *,
        model_name: str | None = None,
        record_id: str | None = None,
        user_id: str | None = None,
        operation: str | None = None,
        since: datetime | None = None,
        until: datetime | None = None,
        limit: int = 100,
        offset: int = 0,
    ) -> list[PrivacyAuditLog]:
        """Query audit log entries with optional filters.

        Args:
            model_name: Filter by model name.
            record_id: Filter by record ID.
            user_id: Filter by user ID.
            operation: Filter by operation type.
            since: Filter entries after this timestamp.
            until: Filter entries before this timestamp.
            limit: Maximum number of entries to return.
            offset: Number of entries to skip.
        """
        stmt = select(PrivacyAuditLog).order_by(PrivacyAuditLog.timestamp.desc())

        if model_name is not None:
            stmt = stmt.where(PrivacyAuditLog.model_name == model_name)
        if record_id is not None:
            stmt = stmt.where(PrivacyAuditLog.record_id == record_id)
        if user_id is not None:
            stmt = stmt.where(PrivacyAuditLog.user_id == user_id)
        if operation is not None:
            stmt = stmt.where(PrivacyAuditLog.operation == operation)
        if since is not None:
            stmt = stmt.where(PrivacyAuditLog.timestamp >= since)
        if until is not None:
            stmt = stmt.where(PrivacyAuditLog.timestamp <= until)

        stmt = stmt.offset(offset).limit(limit)
        result = await self.session.execute(stmt)
        return list(result.scalars().all())
