<?php

declare(strict_types=1);

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

use App\Module\Directory\Domain\Enum\ProspectStatus;
use App\Module\Directory\Domain\Repository\ProspectRepositoryInterface;
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;

use function sprintf;

#[McpTool(name: 'list-prospects', description: 'List prospects, optionally filtered by status (new, contacted, qualified, won, lost).')]
class ListProspectsTool
{
    public function __construct(
        private readonly ProspectRepositoryInterface $prospectRepository,
        private readonly Security $security,
    ) {}

    public function __invoke(?string $status = null): string
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedException('Access denied: ROLE_USER required.');
        }

        $criteria = [];
        if (null !== $status) {
            $statusEnum = ProspectStatus::tryFrom($status);
            if (null === $statusEnum) {
                throw new InvalidArgumentException(sprintf('Invalid status "%s". Allowed: new, contacted, qualified, won, lost.', $status));
            }
            $criteria['status'] = $statusEnum;
        }

        $prospects = $this->prospectRepository->findBy($criteria, ['company' => 'ASC']);

        return json_encode(array_map(static fn ($prospect) => Serializer::prospect($prospect), $prospects));
    }
}
