<?php

declare(strict_types=1);

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

use App\Module\ProjectManagement\Domain\Repository\TaskPriorityRepositoryInterface;
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-priority', description: 'Update a task priority. Only provided fields change.')]
class UpdatePriorityTool
{
    public function __construct(
        private readonly TaskPriorityRepositoryInterface $priorityRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

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

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

        if (null !== $label) {
            $priority->setLabel($label);
        }
        if (null !== $color) {
            $priority->setColor($color);
        }
        $this->entityManager->flush();

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