<?php

declare(strict_types=1);

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

use App\Module\Directory\Domain\Entity\CommercialReport;
use App\Module\Directory\Domain\Enum\ReportType;
use App\Module\Directory\Domain\Repository\ClientRepositoryInterface;
use App\Module\Directory\Domain\Repository\PrestataireRepositoryInterface;
use App\Module\Directory\Domain\Repository\ProspectRepositoryInterface;
use App\Shared\Infrastructure\Mcp\Serializer;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
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-commercial-report',
    description: 'Create a commercial report (admin) attached to exactly one of clientId / prospectId / prestataireId. Type defaults to "note". Allowed types: note, call, meeting, email. Date defaults to today if omitted.'
)]
class CreateCommercialReportTool
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly ClientRepositoryInterface $clientRepository,
        private readonly ProspectRepositoryInterface $prospectRepository,
        private readonly PrestataireRepositoryInterface $prestataireRepository,
        private readonly Security $security,
    ) {}

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

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

        $report = new CommercialReport();
        $report->setSubject($subject);
        $report->setBody($body);

        if (null !== $clientId) {
            $client = $this->clientRepository->findById($clientId);
            if (null === $client) {
                throw new InvalidArgumentException(sprintf('Client with ID %d not found.', $clientId));
            }
            $report->setClient($client);
        }
        if (null !== $prospectId) {
            $prospect = $this->prospectRepository->findById($prospectId);
            if (null === $prospect) {
                throw new InvalidArgumentException(sprintf('Prospect with ID %d not found.', $prospectId));
            }
            $report->setProspect($prospect);
        }
        if (null !== $prestataireId) {
            $prestataire = $this->prestataireRepository->findById($prestataireId);
            if (null === $prestataire) {
                throw new InvalidArgumentException(sprintf('Prestataire with ID %d not found.', $prestataireId));
            }
            $report->setPrestataire($prestataire);
        }

        try {
            $date = null === $occurredAt
                ? new DateTimeImmutable('today')
                : new DateTimeImmutable($occurredAt);
        } catch (Exception $e) {
            throw new InvalidArgumentException(sprintf('Invalid occurredAt "%s": %s', $occurredAt, $e->getMessage()));
        }
        $report->setOccurredAt($date);

        if (null !== $type) {
            $typeEnum = ReportType::tryFrom($type);
            if (null === $typeEnum) {
                throw new InvalidArgumentException(sprintf('Invalid type "%s". Allowed: note, call, meeting, email.', $type));
            }
            $report->setType($typeEnum);
        }

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

        return json_encode(Serializer::commercialReport($report));
    }
}
