<?php

declare(strict_types=1);

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

use App\Module\ProjectManagement\Domain\Repository\TaskTagRepositoryInterface;
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: 'delete-tag', description: 'Delete a global task tag. It is removed from all tasks that use it.')]
class DeleteTagTool
{
    public function __construct(
        private readonly TaskTagRepositoryInterface $tagRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

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

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

        $label = $tag->getLabel();
        $this->entityManager->remove($tag);
        $this->entityManager->flush();

        return json_encode(['success' => true, 'message' => sprintf('Tag "%s" deleted.', $label)]);
    }
}
