<?php

declare(strict_types=1);

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

use App\Module\ProjectManagement\Domain\Repository\ProjectRepositoryInterface;
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-project', description: 'Permanently delete a project and all its tasks (admin). Irreversible.')]
class DeleteProjectTool
{
    public function __construct(
        private readonly ProjectRepositoryInterface $projectRepository,
        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.');
        }

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

        $name = $project->getName();
        $this->entityManager->remove($project);
        $this->entityManager->flush();

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