<?php

declare(strict_types=1);

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

use App\Module\Directory\Domain\Repository\PrestataireRepositoryInterface;
use App\Shared\Infrastructure\Mcp\Serializer;
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-prestataire', description: 'Update a prestataire (admin). Only provided fields change.')]
class UpdatePrestataireTool
{
    public function __construct(
        private readonly PrestataireRepositoryInterface $prestataireRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(
        int $id,
        ?string $name = null,
        ?string $email = null,
        ?string $phone = null,
        ?string $website = null,
    ): 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));
        }

        if (null !== $name) {
            $prestataire->setName($name);
        }
        if (null !== $email) {
            $prestataire->setEmail($email);
        }
        if (null !== $phone) {
            $prestataire->setPhone($phone);
        }
        if (null !== $website) {
            $prestataire->setWebsite($website);
        }

        $this->entityManager->flush();

        return json_encode(Serializer::prestataire($prestataire));
    }
}
