<?php

declare(strict_types=1);

namespace App\Module\Directory\Infrastructure\Mcp\Tool;

use App\Module\Directory\Domain\Repository\PrestataireRepositoryInterface;
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-prestataire', description: 'Delete a prestataire (admin). Cascade removes its contacts, addresses and reports.')]
class DeletePrestataireTool
{
    public function __construct(
        private readonly PrestataireRepositoryInterface $prestataireRepository,
        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.');
        }

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

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

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