<?php

declare(strict_types=1);

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

use App\Module\Directory\Domain\Repository\AddressRepositoryInterface;
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-address',
    description: 'Update an address (admin). Only provided fields change. Parent (client/prospect/prestataire) is immutable.'
)]
class UpdateAddressTool
{
    public function __construct(
        private readonly AddressRepositoryInterface $addressRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

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

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

        if (null !== $label) {
            $address->setLabel($label);
        }
        if (null !== $street) {
            $address->setStreet($street);
        }
        if (null !== $streetComplement) {
            $address->setStreetComplement($streetComplement);
        }
        if (null !== $postalCode) {
            $address->setPostalCode($postalCode);
        }
        if (null !== $city) {
            $address->setCity($city);
        }
        if (null !== $country) {
            if (2 !== strlen($country)) {
                throw new InvalidArgumentException('country must be a 2-letter ISO 3166 alpha-2 code (e.g., FR, BE).');
            }
            $address->setCountry(strtoupper($country));
        }

        $this->entityManager->flush();

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