<?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_entity_history',
    description: 'Get the audit history for a specific entity (machine, piece, composant, product). Returns list of changes with diffs.',
)]
class EntityHistoryTool
{
    use McpToolHelper;

    private const VALID_TYPES = ['machine', 'piece', 'composant', 'product'];

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

    public function __invoke(string $entityType, string $entityId): CallToolResult
    {
        $this->requireRole($this->security, 'ROLE_VIEWER');

        if (!in_array($entityType, self::VALID_TYPES, true)) {
            $this->mcpError('Validation', sprintf(
                'Invalid entityType "%s". Must be one of: %s',
                $entityType,
                implode(', ', self::VALID_TYPES),
            ));
        }

        $logs = $this->auditLogs->findEntityHistory($entityType, $entityId, 200);

        $items = array_map(
            static fn ($log) => [
                'id'             => $log->getId(),
                'action'         => $log->getAction(),
                'diff'           => $log->getDiff(),
                'actorProfileId' => $log->getActorProfileId(),
                'createdAt'      => $log->getCreatedAt()->format(DateTimeInterface::ATOM),
            ],
            $logs,
        );

        return $this->jsonResponse([
            'items' => array_values($items),
            'total' => count($items),
        ]);
    }
}
