<?php

declare(strict_types=1);

namespace App\Module\ProjectManagement\Infrastructure\Mcp\Tool\TaskMeta;

use App\Module\ProjectManagement\Domain\Repository\TaskEffortRepositoryInterface;
use Doctrine\ORM\EntityManagerInterface;
use InvalidArgumentException;
use Mcp\Capability\Attribute\McpTool;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

use function sprintf;

#[McpTool(name: 'update-effort', description: 'Rename a task effort level.')]
class UpdateEffortTool
{
    public function __construct(
        private readonly TaskEffortRepositoryInterface $effortRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(int $id, string $label): string
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedException('Access denied: ROLE_USER required.');
        }

        $effort = $this->effortRepository->findById($id);
        if (null === $effort) {
            throw new InvalidArgumentException(sprintf('TaskEffort with ID %d not found.', $id));
        }

        $effort->setLabel($label);
        $this->entityManager->flush();

        return json_encode(['id' => $effort->getId(), 'label' => $effort->getLabel()]);
    }
}
