<?php

declare(strict_types=1);

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

use App\Module\Directory\Domain\Entity\Prospect;
use App\Module\Directory\Domain\Enum\ProspectStatus;
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: 'create-prospect', description: 'Create a prospect (admin). Only company is required. Status defaults to "new".')]
class CreateProspectTool
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(
        string $company,
        ?string $email = null,
        ?string $phone = null,
        ?string $website = null,
        ?string $status = null,
        ?string $source = null,
        ?string $notes = null,
    ): string {
        if (!$this->security->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedException('Access denied: ROLE_ADMIN required.');
        }

        $prospect = new Prospect();
        $prospect->setCompany($company);
        $prospect->setEmail($email);
        $prospect->setPhone($phone);
        $prospect->setWebsite($website);
        $prospect->setSource($source);
        $prospect->setNotes($notes);

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

        $this->entityManager->persist($prospect);
        $this->entityManager->flush();

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