<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Reference;

use App\Mcp\Tool\Serializer;
use App\Repository\ClientRepository;
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-client', description: 'Update a client (admin). Only provided fields change.')]
class UpdateClientTool
{
    public function __construct(
        private readonly ClientRepository $clientRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(
        int $id,
        ?string $name = null,
        ?string $email = null,
        ?string $phone = null,
        ?string $street = null,
        ?string $city = null,
        ?string $postalCode = null,
    ): string {
        if (!$this->security->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedException('Access denied: ROLE_ADMIN required.');
        }

        $client = $this->clientRepository->find($id);
        if (null === $client) {
            throw new InvalidArgumentException(sprintf('Client with ID %d not found.', $id));
        }

        if (null !== $name) {
            $client->setName($name);
        }
        if (null !== $email) {
            $client->setEmail($email);
        }
        if (null !== $phone) {
            $client->setPhone($phone);
        }
        if (null !== $street) {
            $client->setStreet($street);
        }
        if (null !== $city) {
            $client->setCity($city);
        }
        if (null !== $postalCode) {
            $client->setPostalCode($postalCode);
        }

        $this->entityManager->flush();

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