from __future__ import annotations

from datetime import datetime, timezone
from typing import Any
from uuid import UUID

from src.domain.entities import AuditLogEntity
from src.domain.interfaces import IAuditLogRepository
from src.core.logging import get_logger

logger = get_logger("audit_service")


class AuditService:
    def __init__(self, audit_repo: IAuditLogRepository) -> None:
        self._audit_repo = audit_repo

    async def log_action(
        self,
        action: str,
        resource_type: str,
        *,
        actor_id: UUID | None = None,
        actor_type: str | None = None,
        resource_id: str | None = None,
        old_value: dict | None = None,
        new_value: dict | None = None,
        ip_address: str | None = None,
        user_agent: str | None = None,
        request_id: str | None = None,
    ) -> AuditLogEntity:
        entity = AuditLogEntity(
            actor_id=actor_id,
            actor_type=actor_type,
            action=action,
            resource_type=resource_type,
            resource_id=resource_id,
            old_value=old_value,
            new_value=new_value,
            ip_address=ip_address,
            user_agent=user_agent,
            request_id=request_id,
        )
        created = await self._audit_repo.add(entity)
        return created

    async def list_logs(
        self,
        *,
        actor_id: UUID | None = None,
        action: str | None = None,
        resource_type: str | None = None,
        offset: int = 0,
        limit: int = 50,
    ) -> tuple[list[AuditLogEntity], int]:
        return await self._audit_repo.list_logs(
            actor_id=actor_id,
            action=action,
            resource_type=resource_type,
            offset=offset,
            limit=limit,
        )
