<?php

declare(strict_types=1);

namespace App\Mcp\Tool;

use App\Repository\AuditLogRepository;
use DateTimeInterface;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Result\CallToolResult;
use Symfony\Bundle\SecurityBundle\Security;

#[McpTool(
    name: 'get_activity_log',
    description: 'Get the global activity log with optional filters. Returns paginated audit entries across all entities.',
)]
class ActivityLogTool
{
    use McpToolHelper;

    public function __construct(
        private readonly AuditLogRepository $auditLogs,
        private readonly Security $security,
    ) {}

    public function __invoke(int $page = 1, int $limit = 30, string $entityType = '', string $action = ''): CallToolResult
    {
        $this->requireRole($this->security, 'ROLE_VIEWER');

        $p = $this->paginationParams($page, $limit);

        $filters = [];
        if ('' !== $entityType) {
            $filters['entityType'] = $entityType;
        }
        if ('' !== $action) {
            $filters['action'] = $action;
        }

        $result = $this->auditLogs->findAllPaginated($p['page'], $p['limit'], $filters);

        $items = array_map(
            static function ($log) {
                $snapshot = $log->getSnapshot();

                return [
                    'id'             => $log->getId(),
                    'entityType'     => $log->getEntityType(),
                    'entityId'       => $log->getEntityId(),
                    'entityName'     => $snapshot['name'] ?? null,
                    'action'         => $log->getAction(),
                    'diff'           => $log->getDiff(),
                    'actorProfileId' => $log->getActorProfileId(),
                    'createdAt'      => $log->getCreatedAt()->format(DateTimeInterface::ATOM),
                ];
            },
            $result['items'],
        );

        return $this->paginatedResponse(array_values($items), $result['total'], $p['page'], $p['limit']);
    }
}
