<?php

declare(strict_types=1);

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

use App\Module\Directory\Domain\Repository\ContactRepositoryInterface;
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-contact',
    description: 'Update a contact (admin). Only provided fields change. The parent (client/prospect/prestataire) is immutable — delete then recreate to re-attach.'
)]
class UpdateContactTool
{
    public function __construct(
        private readonly ContactRepositoryInterface $contactRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(
        int $id,
        ?string $firstName = null,
        ?string $lastName = null,
        ?string $jobTitle = null,
        ?string $email = null,
        ?string $phonePrimary = null,
        ?string $phoneSecondary = null,
    ): string {
        if (!$this->security->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedException('Access denied: ROLE_ADMIN required.');
        }

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

        if (null !== $firstName) {
            $contact->setFirstName($firstName);
        }
        if (null !== $lastName) {
            $contact->setLastName($lastName);
        }
        if (null !== $jobTitle) {
            $contact->setJobTitle($jobTitle);
        }
        if (null !== $email) {
            $contact->setEmail($email);
        }
        if (null !== $phonePrimary) {
            $contact->setPhonePrimary($phonePrimary);
        }
        if (null !== $phoneSecondary) {
            $contact->setPhoneSecondary($phoneSecondary);
        }

        $this->entityManager->flush();

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