<?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 InvalidArgumentException;
use Mcp\Capability\Attribute\McpTool;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

#[McpTool(
    name: 'list-contacts',
    description: 'List contacts, optionally filtered by parent (at most one of clientId / prospectId / prestataireId).'
)]
class ListContactsTool
{
    public function __construct(
        private readonly ContactRepositoryInterface $contactRepository,
        private readonly Security $security,
    ) {}

    public function __invoke(
        ?int $clientId = null,
        ?int $prospectId = null,
        ?int $prestataireId = null,
    ): string {
        if (!$this->security->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedException('Access denied: ROLE_ADMIN required.');
        }

        $filters = array_filter([$clientId, $prospectId, $prestataireId], static fn ($v) => null !== $v);
        if (count($filters) > 1) {
            throw new InvalidArgumentException('At most one of clientId, prospectId or prestataireId can be provided.');
        }

        $criteria = [];
        if (null !== $clientId) {
            $criteria['client'] = $clientId;
        }
        if (null !== $prospectId) {
            $criteria['prospect'] = $prospectId;
        }
        if (null !== $prestataireId) {
            $criteria['prestataire'] = $prestataireId;
        }

        $contacts = $this->contactRepository->findBy($criteria, ['lastName' => 'ASC']);

        return json_encode(array_map(fn ($c) => Serializer::contact($c), $contacts));
    }
}
