<?php

declare(strict_types=1);

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

use App\Module\Directory\Domain\Entity\Address;
use App\Module\Directory\Domain\Entity\Client;
use App\Module\Directory\Domain\Entity\CommercialReport;
use App\Module\Directory\Domain\Entity\Contact;
use App\Module\Directory\Domain\Entity\Prospect;
use App\Module\Directory\Domain\Enum\ProspectStatus;
use App\Module\Directory\Domain\Repository\ProspectRepositoryInterface;
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: 'convert-prospect', description: 'Convert a prospect into a client (admin). Idempotent: returns the prospect unchanged if already converted.')]
class ConvertProspectTool
{
    public function __construct(
        private readonly ProspectRepositoryInterface $prospectRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(int $id): string
    {
        if (!$this->security->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedException('Access denied: ROLE_ADMIN required.');
        }

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

        if (null === $prospect->getConvertedClient()) {
            $client = new Client();
            $client->setName((string) $prospect->getCompany());
            $client->setEmail($prospect->getEmail());
            $client->setPhone($prospect->getPhone());
            $client->setWebsite($prospect->getWebsite());

            $this->entityManager->persist($client);

            $this->reassignContacts($prospect, $client);
            $this->reassignAddresses($prospect, $client);
            $this->reassignReports($prospect, $client);

            $prospect->setConvertedClient($client);
            $prospect->setStatus(ProspectStatus::Won);

            $this->entityManager->flush();
        }

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

    private function reassignContacts(Prospect $prospect, Client $client): void
    {
        foreach ($this->entityManager->getRepository(Contact::class)->findBy(['prospect' => $prospect]) as $contact) {
            $contact->setClient($client);
            $contact->setProspect(null);
        }
    }

    private function reassignAddresses(Prospect $prospect, Client $client): void
    {
        foreach ($this->entityManager->getRepository(Address::class)->findBy(['prospect' => $prospect]) as $address) {
            $address->setClient($client);
            $address->setProspect(null);
        }
    }

    private function reassignReports(Prospect $prospect, Client $client): void
    {
        foreach ($this->entityManager->getRepository(CommercialReport::class)->findBy(['prospect' => $prospect]) as $report) {
            $report->setClient($client);
            $report->setProspect(null);
        }
    }
}
