<?php

declare(strict_types=1);

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

use App\Module\ProjectManagement\Domain\Repository\TaskStatusRepositoryInterface;
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-status', description: 'Delete a task status from its workflow (admin). Fails at the database level if tasks still use it.')]
class DeleteStatusTool
{
    public function __construct(
        private readonly TaskStatusRepositoryInterface $statusRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

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

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

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

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